Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Refactor story-adding and coverart-importing code, fixing some cases of missing coverart in the process
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:677361353d03bc0fcad9d5c052b0e9024e16531f
User & Date: brandon 2018-12-10 02:01:40
Context
2018-12-10
02:17
Fix yet another case of trying to take action when a library item is not selected Leaf check-in: 9e8267681c user: brandon tags: trunk
02:01
Refactor story-adding and coverart-importing code, fixing some cases of missing coverart in the process check-in: 677361353d user: brandon tags: trunk
2018-12-06
21:40
Fix module name check-in: 1cb7348a70 user: brandon tags: trunk
Changes

Changes to src/grotesque/db/__init__.py.

68
69
70
71
72
73
74
75
76
77
78
79
80
81
82



83
84
85
86
87
88
89
..
95
96
97
98
99
100
101



















































102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128

129
130
131
132
133

134
135
136



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
        return None
    story_id = addremove.add_story_meta(conn, ifid, ific_story, ific_source)
    addremove.add_story_cover(conn, story_id, story_file, ific_story,
                              fetch_coverart)
    return story_id


def add_story_from_file(conn, settings, filename, fetch_metadata,
                        fetch_coverart):
    fail = False
    # Check if this file has been added already
    file_release = query.select_release_by_uri(conn, filename)
    if file_release is not None:
        return (None, None)
    # Get the format and the interpreter command



    try:
        ifformat = treatyofbabel.deduce_format(filename)
    except BabelError as e:
        warnings.warn("{0} is of an unknown format; skipping".format(filename))
        raise e
    except ValueError as e:
        warnings.warn("{0} does not contain any data".format(filename))
................................................................................
            buf = h.read()
        if is_win32_executable(buf):
            raw_format = "win32"
        else:
            raw_format = "dos"
    else:
        raw_format = ifformat.strip()



















































    try:
        command = settings.get_launcher(raw_format)
    except:
        command = None
    format_rec = query.select_format_by_name(conn, ifformat)
    if format_rec is not None:
        format_id = format_rec["id"]
    else:
        format_id = addremove.add_story_format(conn, ifformat, command)
        # Check if any of this file's IFIDs have already been added
    try:
        ifids = treatyofbabel.get_ifids(filename)
    except (BabelError, ValueError) as e:
        raise e
    new_ifids = []
    story_id = None
    for ifid in ifids:
        release_rec = query.select_release(conn, ifid)
        if release_rec is None:
            new_ifids.append(ifid)
            continue
        if story_id is None:
            story_id = release_rec["story_id"]
        # If a release with that IFID has been previously added,
        # update its associated file
        query.update_release(conn, ifid, {"uri": filename,
                                          "format_id": format_id})

    if not new_ifids:
        return (None, None)
    if story_id is None:
        for ifid in new_ifids:
            ific_story, ific_source = addremove.get_ifiction(filename, ifid,

                                                             fetch_metadata)
            if ific_story is None:
                continue



            story_id = addremove.add_story_meta(conn, ifid, ific_story,
                                                ific_source)
            addremove.add_story_cover(conn, story_id, filename, ific_story,
                                      fetch_coverart)
            break
    if story_id is None:
        story_id = addremove.add_story_stub(conn, ifid, filename)
        fail = True
    for ifid in new_ifids:
        addremove.add_story_release(conn, story_id, ifid, raw_format, command,
                                    os.path.realpath(filename))
    # Assume that the user wants the most recent version added
    # to be the default release
    query.update_story(conn, story_id, {"default_release": new_ifids[0]})
    return (story_id, fail)







|
<
<
<

|
<
<
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|



|
|




<
<
<
<
<
<
<
<
<
<
<
<
<
>



<
<
>
|
|
<
>
>
>




<
<
<
<







68
69
70
71
72
73
74
75



76
77


78
79
80
81
82
83
84
85
86
87
..
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164













165
166
167
168


169
170
171

172
173
174
175
176
177
178




179
180
181
182
183
184
185
        return None
    story_id = addremove.add_story_meta(conn, ifid, ific_story, ific_source)
    addremove.add_story_cover(conn, story_id, story_file, ific_story,
                              fetch_coverart)
    return story_id


def _file_in_db(conn, filename):



    file_release = query.select_release_by_uri(conn, filename)
    return file_release is not None




def _get_raw_format(filename):
    try:
        ifformat = treatyofbabel.deduce_format(filename)
    except BabelError as e:
        warnings.warn("{0} is of an unknown format; skipping".format(filename))
        raise e
    except ValueError as e:
        warnings.warn("{0} does not contain any data".format(filename))
................................................................................
            buf = h.read()
        if is_win32_executable(buf):
            raw_format = "win32"
        else:
            raw_format = "dos"
    else:
        raw_format = ifformat.strip()
    return raw_format


def _get_story_new_ifids(conn, story_ifids, filename, format_id):
    new_ifids = []
    story_ids = set()
    for ifid in story_ifids:
        release_rec = query.select_release(conn, ifid)
        if release_rec is None:
            new_ifids.append(ifid)
            continue
        story_ids.add(release_rec["story_id"])
        if release_rec["uri"] != filename:
            # If a release with that IFID has been previously added,
            # update its associated file
            query.update_release(conn, ifid, {"uri": filename,
                                              "format_id": format_id})
    if len(story_ids) == 0:
        return (None, new_ifids)
    if len(story_ids) > 1:
        raise Exception(("Multiple stories are linked to the IFIDs associated ",
                         "with file {0}".format(filename)))
    story_id = list(story_ids)[0]
    return (story_id, new_ifids)


def _get_story_ific(filename, ifids, fetch_metadata):
    ific_story = None
    if fetch_metadata:
        for ifid in ifids:
            ific_story, ific_source = addremove.get_ifiction(filename, ifid,
                                                             True)
            ific_ifid = ifid
            if ific_story is not None:
                break
    if ific_story is None:
        for ifid in ifids:
            ific_story, ific_source = addremove.get_ifiction(filename, ifid,
                                                             False)
            ific_ifid = ifid
    return (ific_story, ific_source, ific_ifid)


def add_story_from_file(conn, settings, filename, fetch_metadata,
                        fetch_coverart):
    fail = False
    # Check if this file has been added already
    if _file_in_db(conn, filename):
        return (None, None)
    # Get the format and the interpreter command
    raw_format = _get_raw_format(filename)
    try:
        command = settings.get_launcher(raw_format)
    except:
        command = None
    format_rec = query.select_format_by_name(conn, raw_format)
    if format_rec is not None:
        format_id = format_rec["id"]
    else:
        format_id = addremove.add_story_format(conn, raw_format, command)
    # Check if any of this file's IFIDs have already been added
    try:
        ifids = treatyofbabel.get_ifids(filename)
    except (BabelError, ValueError) as e:
        raise e













    story_id, new_ifids = _get_story_new_ifids(conn, ifids, filename, format_id)
    if not new_ifids:
        return (None, None)
    if story_id is None:


        ific_story, ific_source, ifid = _get_story_ific(filename, ifids,
                                                        fetch_metadata)
        if ific_story is None:

            story_id = addremove.add_story_stub(conn, ifid, filename)
            fail = True
        else:
            story_id = addremove.add_story_meta(conn, ifid, ific_story,
                                                ific_source)
            addremove.add_story_cover(conn, story_id, filename, ific_story,
                                      fetch_coverart)




    for ifid in new_ifids:
        addremove.add_story_release(conn, story_id, ifid, raw_format, command,
                                    os.path.realpath(filename))
    # Assume that the user wants the most recent version added
    # to be the default release
    query.update_story(conn, story_id, {"default_release": new_ifids[0]})
    return (story_id, fail)

Changes to src/grotesque/db/addremove.py.

163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195

196



197


198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223

















224







225
226
227
228
229
230
231
232
233
234
235








236






237
238
239
240
241
242
243
244
...
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
        if not genre_row:
            genre_id = query.insert_genre(conn, genre.lower())
        else:
            genre_id = genre_row["id"]
        query.add_genre_to_story(conn, genre_id, story_id)


def add_story_cover(conn, story_id, filename, ific_story, fetch_coverart):
    orig_cover = query.select_cover_by_story(conn, story_id)
    if filename is not None:
        try:
            cover = treatyofbabel.get_cover(filename)
        except BabelError:
            cover = None
        if cover is not None:
            if orig_cover is not None:
                query.update_cover(conn, orig_cover["id"],
                                      {"height": cover.height,
                                       "width": cover.width,
                                       "format": cover.img_format,
                                       "description": cover.description,
                                       "data": cover.data})
            else:
                query.insert_cover(conn, story_id, cover.img_format,
                                   cover.height, cover.width, cover.description,
                                   cover.data)
            return True
    annotation = ifiction.get_annotation(ific_story)
    if annotation is None:
        return False
    if fetch_coverart and "ifdb" in annotation:
        tuid = annotation["ifdb"].get("tuid")
        if tuid is None:

            return False



        data = ifdb.fetch_cover(tuid)


        if data is None:
            return False
        img_format = _imgfuncs.deduce_img_format(data)
        if img_format == "jpeg":
            width, height = _imgfuncs.get_jpeg_dim(data)
        elif img_format == "png":
            width, height = _imgfuncs.get_png_dim(data)
        elif img_format == "gif":
            width, height = _imgfuncs.get_gif_dim(data)
        else:
            biblio = query.select_story(conn, story_id)
            warnings.warn("unsupported image format for {0}".format(
                biblio["title"]))
            return False
        description = None
        if orig_cover is not None:
            query.update_cover(conn, orig_cover["id"],
                               {"height": height,
                                "width": width,
                                "format": img_format,
                                "description": description,
                                "data": data})
        else:
            query.insert_cover(
                conn, story_id, img_format, height, width,
                description, data)

















    else:







        cover_info = ifiction.get_cover(ific_story)
        if cover_info is None:
            return False
        if orig_cover is not None and orig_cover["data"]:
            warnings.warn("cowardly refusing to replace existing cover data "
                          "with IFiction skeleton data")
            return False
        query.insert_cover(
            conn, story_id, cover_info["format"],
            cover_info["height"], cover_info["width"],
            cover_info["description"], "")








    return True








def add_story_annotation(conn, story_id, annotation):
    if (annotation is not None and
            "grotesque" in annotation and
            "rating" in annotation["grotesque"]):
        rating = float(annotation["grotesque"]["rating"])
        if not rating:
................................................................................


def get_ifiction(filename, ifid, fetch_metadata):
    ific_story = None
    ific_source = None
    if fetch_metadata:
        ific_story = ifdb.fetch_ifiction(ifid=ifid)
        ific_source = "ifdb"
    if ific_story is None:
        # Either we're not fetching from IFDB or fetching from there
        # failed.  So, try to extract metadata from the file itself.
        try:
            ific_str = treatyofbabel.get_meta(filename)
        except:
            warnings.warn("no IFiction found for {0}".format(filename))
            return (None, None)
        if not ific_str:
            warnings.warn("no IFiction found for {0}".format(filename))
            return (None, None)
        try:
            ific_dom = ifiction.get_ifiction_dom(ific_str)
        except IFictionError:
            warnings.warn("malformed IFiction found for {0}".format(filename))
            return (None, None)
        stories = ifiction.get_all_stories(ific_dom)
        ific_story = stories[0]
        ific_source = "extract"
    return (ific_story, ific_source)


def clean_story_authors(conn, story_id):
    if not story_id:
        return
    author_ids = query.select_story_authors(conn, story_id)
    for (author_id,) in author_ids:







|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<



<
<
<
>
|
>
>
>
|
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

>
>
>
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>








 







<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|







163
164
165
166
167
168
169
170



















171
172
173



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
...
361
362
363
364
365
366
367

368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385

386
387
388
389
390
391
392
393
        if not genre_row:
            genre_id = query.insert_genre(conn, genre.lower())
        else:
            genre_id = genre_row["id"]
        query.add_genre_to_story(conn, genre_id, story_id)


def _fetch_story_cover(conn, story_id, ific_story, orig_cover):



















    annotation = ifiction.get_annotation(ific_story)
    if annotation is None:
        return False



    if "ifdb" not in annotation:
        return False
    if "cover_url" in annotation["ifdb"]:
        data = ifdb.fetch_cover(url=annotation["ifdb"]["cover_url"])
    elif "tuid" in annotation["ifdb"]:
        data = ifdb.fetch_cover(tuid=annotation["ifdb"]["tuid"])
    else:
        return False
    if data is None:
        return False
    img_format = _imgfuncs.deduce_img_format(data)
    if img_format == "jpeg":
        width, height = _imgfuncs.get_jpeg_dim(data)
    elif img_format == "png":
        width, height = _imgfuncs.get_png_dim(data)
    elif img_format == "gif":
        width, height = _imgfuncs.get_gif_dim(data)
    else:
        biblio = query.select_story(conn, story_id)
        warnings.warn("unsupported image format for {0}".format(
            biblio["title"]))
        return False
    description = None
    if orig_cover is not None:
        query.update_cover(conn, orig_cover["id"],
                           {"height": height,
                            "width": width,
                            "format": img_format,
                            "description": description,
                            "data": data})
    else:
        query.insert_cover(
            conn, story_id, img_format, height, width,
            description, data)
    return True


def _extract_story_cover(conn, story_id, filename, orig_cover):
    try:
        cover = treatyofbabel.get_cover(filename)
    except BabelError:
        return False
    if cover is None:
        return False
    if orig_cover is not None:
        query.update_cover(conn, orig_cover["id"],
                           {"height": cover.height,
                            "width": cover.width,
                            "format": cover.img_format,
                            "description": cover.description,
                            "data": cover.data})
    else:
        query.insert_cover(conn, story_id, cover.img_format,
                           cover.height, cover.width, cover.description,
                           cover.data)
    return True


def _add_cover_stub(conn, story_id, ific_story, orig_cover):
    cover_info = ifiction.get_cover(ific_story)
    if cover_info is None:
        return False
    if orig_cover is not None and orig_cover["data"]:
        warnings.warn("cowardly refusing to replace existing cover data "
                      "with IFiction skeleton data")
        return False
    query.insert_cover(
        conn, story_id, cover_info["format"],
        cover_info["height"], cover_info["width"],
        cover_info["description"], "")


def add_story_cover(conn, story_id, filename, ific_story, fetch_coverart):
    orig_cover = query.select_cover_by_story(conn, story_id)
    if fetch_coverart:
        fetch_success = _fetch_story_cover(conn, story_id, ific_story,
                                           orig_cover)
        if fetch_success:
            return True
    if filename is not None:
        extract_success = _extract_story_cover(conn, story_id, filename,
                                               orig_cover)
        if extract_success:
            return True
    return _add_cover_stub(conn, story_id, ific_story, orig_cover)


def add_story_annotation(conn, story_id, annotation):
    if (annotation is not None and
            "grotesque" in annotation and
            "rating" in annotation["grotesque"]):
        rating = float(annotation["grotesque"]["rating"])
        if not rating:
................................................................................


def get_ifiction(filename, ifid, fetch_metadata):
    ific_story = None
    ific_source = None
    if fetch_metadata:
        ific_story = ifdb.fetch_ifiction(ifid=ifid)

        return (ific_story, "ifdb")
    # Either we're not fetching from IFDB or fetching from there
    # failed.  So, try to extract metadata from the file itself.
    try:
        ific_str = treatyofbabel.get_meta(filename)
    except:
        warnings.warn("no IFiction found for {0}".format(filename))
        return (None, None)
    if not ific_str:
        warnings.warn("no IFiction found for {0}".format(filename))
        return (None, None)
    try:
        ific_dom = ifiction.get_ifiction_dom(ific_str)
    except IFictionError:
        warnings.warn("malformed IFiction found for {0}".format(filename))
        return (None, None)
    stories = ifiction.get_all_stories(ific_dom)
    ific_story = stories[0]

    return (ific_story, "extract")


def clean_story_authors(conn, story_id):
    if not story_id:
        return
    author_ids = query.select_story_authors(conn, story_id)
    for (author_id,) in author_ids:

Changes to src/grotesque/ifdb.py.

56
57
58
59
60
61
62
63
64
65


66
67
68
69
70
71
72
73
    if not ificstories or len(ificstories) == 0:
        return None
    ificstory = ificstories[0]
    ifiction.move_extra_to_annotation(ificdom, ificstory, ["ifdb"])
    return ificstory


def fetch_cover(tuid=None, ifid=None):
    if tuid is None and ifid is None:
        return None


    if tuid is not None:
        cover_url = ''.join(["https://ifdb.tads.org/viewgame?ifiction&id=",
                             tuid, "&coverart"])
    else:
        cover_url = ''.join(["https://ifdb.tads.org/viewgame?ifiction&ifid=",
                             ifid, "&coverart"])
    try:
        cover_file = urllib2.urlopen(cover_url)







|
|

>
>
|







56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    if not ificstories or len(ificstories) == 0:
        return None
    ificstory = ificstories[0]
    ifiction.move_extra_to_annotation(ificdom, ificstory, ["ifdb"])
    return ificstory


def fetch_cover(url=None, tuid=None, ifid=None):
    if url is None and tuid is None and ifid is None:
        return None
    if url is not None:
        cover_url = url
    elif tuid is not None:
        cover_url = ''.join(["https://ifdb.tads.org/viewgame?ifiction&id=",
                             tuid, "&coverart"])
    else:
        cover_url = ''.join(["https://ifdb.tads.org/viewgame?ifiction&ifid=",
                             ifid, "&coverart"])
    try:
        cover_file = urllib2.urlopen(cover_url)