id int64 0 458k | file_name stringlengths 4 119 | file_path stringlengths 14 227 | content stringlengths 24 9.96M | size int64 24 9.96M | language stringclasses 1 value | extension stringclasses 14 values | total_lines int64 1 219k | avg_line_length float64 2.52 4.63M | max_line_length int64 5 9.91M | alphanum_fraction float64 0 1 | repo_name stringlengths 7 101 | repo_stars int64 100 139k | repo_forks int64 0 26.4k | repo_open_issues int64 0 2.27k | repo_license stringclasses 12 values | repo_extraction_date stringclasses 433 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
21,200 | constants.py | evilhero_mylar/lib/transmissionrpc/constants.py | # -*- coding: utf-8 -*-
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
import logging
from six import iteritems
LOGGER = logging.getLogger('transmissionrpc')
LOGGER.setLevel(logging.ERROR)
def mirror_dict(source):
"""
Creates a dictionary with all values as keys and all keys as values.
"""
source.update(dict((value, key) for key, value in iteritems(source)))
return source
DEFAULT_PORT = 9091
DEFAULT_TIMEOUT = 30.0
TR_PRI_LOW = -1
TR_PRI_NORMAL = 0
TR_PRI_HIGH = 1
PRIORITY = mirror_dict({
'low' : TR_PRI_LOW,
'normal' : TR_PRI_NORMAL,
'high' : TR_PRI_HIGH
})
TR_RATIOLIMIT_GLOBAL = 0 # follow the global settings
TR_RATIOLIMIT_SINGLE = 1 # override the global settings, seeding until a certain ratio
TR_RATIOLIMIT_UNLIMITED = 2 # override the global settings, seeding regardless of ratio
RATIO_LIMIT = mirror_dict({
'global' : TR_RATIOLIMIT_GLOBAL,
'single' : TR_RATIOLIMIT_SINGLE,
'unlimited' : TR_RATIOLIMIT_UNLIMITED
})
TR_IDLELIMIT_GLOBAL = 0 # follow the global settings
TR_IDLELIMIT_SINGLE = 1 # override the global settings, seeding until a certain idle time
TR_IDLELIMIT_UNLIMITED = 2 # override the global settings, seeding regardless of activity
IDLE_LIMIT = mirror_dict({
'global' : TR_RATIOLIMIT_GLOBAL,
'single' : TR_RATIOLIMIT_SINGLE,
'unlimited' : TR_RATIOLIMIT_UNLIMITED
})
# A note on argument maps
# These maps are used to verify *-set methods. The information is structured in
# a tree.
# set +- <argument1> - [<type>, <added version>, <removed version>, <previous argument name>, <next argument name>, <description>]
# | +- <argument2> - [<type>, <added version>, <removed version>, <previous argument name>, <next argument name>, <description>]
# |
# get +- <argument1> - [<type>, <added version>, <removed version>, <previous argument name>, <next argument name>, <description>]
# +- <argument2> - [<type>, <added version>, <removed version>, <previous argument name>, <next argument name>, <description>]
# Arguments for torrent methods
TORRENT_ARGS = {
'get' : {
'activityDate': ('number', 1, None, None, None, 'Last time of upload or download activity.'),
'addedDate': ('number', 1, None, None, None, 'The date when this torrent was first added.'),
'announceResponse': ('string', 1, 7, None, None, 'The announce message from the tracker.'),
'announceURL': ('string', 1, 7, None, None, 'Current announce URL.'),
'bandwidthPriority': ('number', 5, None, None, None, 'Bandwidth priority. Low (-1), Normal (0) or High (1).'),
'comment': ('string', 1, None, None, None, 'Torrent comment.'),
'corruptEver': ('number', 1, None, None, None, 'Number of bytes of corrupt data downloaded.'),
'creator': ('string', 1, None, None, None, 'Torrent creator.'),
'dateCreated': ('number', 1, None, None, None, 'Torrent creation date.'),
'desiredAvailable': ('number', 1, None, None, None, 'Number of bytes avalable and left to be downloaded.'),
'doneDate': ('number', 1, None, None, None, 'The date when the torrent finished downloading.'),
'downloadDir': ('string', 4, None, None, None, 'The directory path where the torrent is downloaded to.'),
'downloadedEver': ('number', 1, None, None, None, 'Number of bytes of good data downloaded.'),
'downloaders': ('number', 4, 7, None, None, 'Number of downloaders.'),
'downloadLimit': ('number', 1, None, None, None, 'Download limit in Kbps.'),
'downloadLimited': ('boolean', 5, None, None, None, 'Download limit is enabled'),
'downloadLimitMode': ('number', 1, 5, None, None, 'Download limit mode. 0 means global, 1 means signle, 2 unlimited.'),
'error': ('number', 1, None, None, None, 'Kind of error. 0 means OK, 1 means tracker warning, 2 means tracker error, 3 means local error.'),
'errorString': ('number', 1, None, None, None, 'Error message.'),
'eta': ('number', 1, None, None, None, 'Estimated number of seconds left when downloading or seeding. -1 means not available and -2 means unknown.'),
'etaIdle': ('number', 15, None, None, None, 'Estimated number of seconds left until the idle time limit is reached. -1 means not available and -2 means unknown.'),
'files': ('array', 1, None, None, None, 'Array of file object containing key, bytesCompleted, length and name.'),
'fileStats': ('array', 5, None, None, None, 'Aray of file statistics containing bytesCompleted, wanted and priority.'),
'hashString': ('string', 1, None, None, None, 'Hashstring unique for the torrent even between sessions.'),
'haveUnchecked': ('number', 1, None, None, None, 'Number of bytes of partial pieces.'),
'haveValid': ('number', 1, None, None, None, 'Number of bytes of checksum verified data.'),
'honorsSessionLimits': ('boolean', 5, None, None, None, 'True if session upload limits are honored'),
'id': ('number', 1, None, None, None, 'Session unique torrent id.'),
'isFinished': ('boolean', 9, None, None, None, 'True if the torrent is finished. Downloaded and seeded.'),
'isPrivate': ('boolean', 1, None, None, None, 'True if the torrent is private.'),
'isStalled': ('boolean', 14, None, None, None, 'True if the torrent has stalled (been idle for a long time).'),
'lastAnnounceTime': ('number', 1, 7, None, None, 'The time of the last announcement.'),
'lastScrapeTime': ('number', 1, 7, None, None, 'The time af the last successful scrape.'),
'leechers': ('number', 1, 7, None, None, 'Number of leechers.'),
'leftUntilDone': ('number', 1, None, None, None, 'Number of bytes left until the download is done.'),
'magnetLink': ('string', 7, None, None, None, 'The magnet link for this torrent.'),
'manualAnnounceTime': ('number', 1, None, None, None, 'The time until you manually ask for more peers.'),
'maxConnectedPeers': ('number', 1, None, None, None, 'Maximum of connected peers.'),
'metadataPercentComplete': ('number', 7, None, None, None, 'Download progress of metadata. 0.0 to 1.0.'),
'name': ('string', 1, None, None, None, 'Torrent name.'),
'nextAnnounceTime': ('number', 1, 7, None, None, 'Next announce time.'),
'nextScrapeTime': ('number', 1, 7, None, None, 'Next scrape time.'),
'peer-limit': ('number', 5, None, None, None, 'Maximum number of peers.'),
'peers': ('array', 2, None, None, None, 'Array of peer objects.'),
'peersConnected': ('number', 1, None, None, None, 'Number of peers we are connected to.'),
'peersFrom': ('object', 1, None, None, None, 'Object containing download peers counts for different peer types.'),
'peersGettingFromUs': ('number', 1, None, None, None, 'Number of peers we are sending data to.'),
'peersKnown': ('number', 1, 13, None, None, 'Number of peers that the tracker knows.'),
'peersSendingToUs': ('number', 1, None, None, None, 'Number of peers sending to us'),
'percentDone': ('double', 5, None, None, None, 'Download progress of selected files. 0.0 to 1.0.'),
'pieces': ('string', 5, None, None, None, 'String with base64 encoded bitfield indicating finished pieces.'),
'pieceCount': ('number', 1, None, None, None, 'Number of pieces.'),
'pieceSize': ('number', 1, None, None, None, 'Number of bytes in a piece.'),
'priorities': ('array', 1, None, None, None, 'Array of file priorities.'),
'queuePosition': ('number', 14, None, None, None, 'The queue position.'),
'rateDownload': ('number', 1, None, None, None, 'Download rate in bps.'),
'rateUpload': ('number', 1, None, None, None, 'Upload rate in bps.'),
'recheckProgress': ('double', 1, None, None, None, 'Progress of recheck. 0.0 to 1.0.'),
'secondsDownloading': ('number', 15, None, None, None, ''),
'secondsSeeding': ('number', 15, None, None, None, ''),
'scrapeResponse': ('string', 1, 7, None, None, 'Scrape response message.'),
'scrapeURL': ('string', 1, 7, None, None, 'Current scrape URL'),
'seeders': ('number', 1, 7, None, None, 'Number of seeders reported by the tracker.'),
'seedIdleLimit': ('number', 10, None, None, None, 'Idle limit in minutes.'),
'seedIdleMode': ('number', 10, None, None, None, 'Use global (0), torrent (1), or unlimited (2) limit.'),
'seedRatioLimit': ('double', 5, None, None, None, 'Seed ratio limit.'),
'seedRatioMode': ('number', 5, None, None, None, 'Use global (0), torrent (1), or unlimited (2) limit.'),
'sizeWhenDone': ('number', 1, None, None, None, 'Size of the torrent download in bytes.'),
'startDate': ('number', 1, None, None, None, 'The date when the torrent was last started.'),
'status': ('number', 1, None, None, None, 'Current status, see source'),
'swarmSpeed': ('number', 1, 7, None, None, 'Estimated speed in Kbps in the swarm.'),
'timesCompleted': ('number', 1, 7, None, None, 'Number of successful downloads reported by the tracker.'),
'trackers': ('array', 1, None, None, None, 'Array of tracker objects.'),
'trackerStats': ('object', 7, None, None, None, 'Array of object containing tracker statistics.'),
'totalSize': ('number', 1, None, None, None, 'Total size of the torrent in bytes'),
'torrentFile': ('string', 5, None, None, None, 'Path to .torrent file.'),
'uploadedEver': ('number', 1, None, None, None, 'Number of bytes uploaded, ever.'),
'uploadLimit': ('number', 1, None, None, None, 'Upload limit in Kbps'),
'uploadLimitMode': ('number', 1, 5, None, None, 'Upload limit mode. 0 means global, 1 means signle, 2 unlimited.'),
'uploadLimited': ('boolean', 5, None, None, None, 'Upload limit enabled.'),
'uploadRatio': ('double', 1, None, None, None, 'Seed ratio.'),
'wanted': ('array', 1, None, None, None, 'Array of booleans indicated wanted files.'),
'webseeds': ('array', 1, None, None, None, 'Array of webseeds objects'),
'webseedsSendingToUs': ('number', 1, None, None, None, 'Number of webseeds seeding to us.'),
},
'set': {
'bandwidthPriority': ('number', 5, None, None, None, 'Priority for this transfer.'),
'downloadLimit': ('number', 5, None, 'speed-limit-down', None, 'Set the speed limit for download in Kib/s.'),
'downloadLimited': ('boolean', 5, None, 'speed-limit-down-enabled', None, 'Enable download speed limiter.'),
'files-wanted': ('array', 1, None, None, None, "A list of file id's that should be downloaded."),
'files-unwanted': ('array', 1, None, None, None, "A list of file id's that shouldn't be downloaded."),
'honorsSessionLimits': ('boolean', 5, None, None, None, "Enables or disables the transfer to honour the upload limit set in the session."),
'location': ('array', 1, None, None, None, 'Local download location.'),
'peer-limit': ('number', 1, None, None, None, 'The peer limit for the torrents.'),
'priority-high': ('array', 1, None, None, None, "A list of file id's that should have high priority."),
'priority-low': ('array', 1, None, None, None, "A list of file id's that should have normal priority."),
'priority-normal': ('array', 1, None, None, None, "A list of file id's that should have low priority."),
'queuePosition': ('number', 14, None, None, None, 'Position of this transfer in its queue.'),
'seedIdleLimit': ('number', 10, None, None, None, 'Seed inactivity limit in minutes.'),
'seedIdleMode': ('number', 10, None, None, None, 'Seed inactivity mode. 0 = Use session limit, 1 = Use transfer limit, 2 = Disable limit.'),
'seedRatioLimit': ('double', 5, None, None, None, 'Seeding ratio.'),
'seedRatioMode': ('number', 5, None, None, None, 'Which ratio to use. 0 = Use session limit, 1 = Use transfer limit, 2 = Disable limit.'),
'speed-limit-down': ('number', 1, 5, None, 'downloadLimit', 'Set the speed limit for download in Kib/s.'),
'speed-limit-down-enabled': ('boolean', 1, 5, None, 'downloadLimited', 'Enable download speed limiter.'),
'speed-limit-up': ('number', 1, 5, None, 'uploadLimit', 'Set the speed limit for upload in Kib/s.'),
'speed-limit-up-enabled': ('boolean', 1, 5, None, 'uploadLimited', 'Enable upload speed limiter.'),
'trackerAdd': ('array', 10, None, None, None, 'Array of string with announce URLs to add.'),
'trackerRemove': ('array', 10, None, None, None, 'Array of ids of trackers to remove.'),
'trackerReplace': ('array', 10, None, None, None, 'Array of (id, url) tuples where the announce URL should be replaced.'),
'uploadLimit': ('number', 5, None, 'speed-limit-up', None, 'Set the speed limit for upload in Kib/s.'),
'uploadLimited': ('boolean', 5, None, 'speed-limit-up-enabled', None, 'Enable upload speed limiter.'),
},
'add': {
'bandwidthPriority': ('number', 8, None, None, None, 'Priority for this transfer.'),
'download-dir': ('string', 1, None, None, None, 'The directory where the downloaded contents will be saved in.'),
'cookies': ('string', 13, None, None, None, 'One or more HTTP cookie(s).'),
'filename': ('string', 1, None, None, None, "A file path or URL to a torrent file or a magnet link."),
'files-wanted': ('array', 1, None, None, None, "A list of file id's that should be downloaded."),
'files-unwanted': ('array', 1, None, None, None, "A list of file id's that shouldn't be downloaded."),
'metainfo': ('string', 1, None, None, None, 'The content of a torrent file, base64 encoded.'),
'paused': ('boolean', 1, None, None, None, 'If True, does not start the transfer when added.'),
'peer-limit': ('number', 1, None, None, None, 'Maximum number of peers allowed.'),
'priority-high': ('array', 1, None, None, None, "A list of file id's that should have high priority."),
'priority-low': ('array', 1, None, None, None, "A list of file id's that should have low priority."),
'priority-normal': ('array', 1, None, None, None, "A list of file id's that should have normal priority."),
}
}
# Arguments for session methods
SESSION_ARGS = {
'get': {
"alt-speed-down": ('number', 5, None, None, None, 'Alternate session download speed limit (in Kib/s).'),
"alt-speed-enabled": ('boolean', 5, None, None, None, 'True if alternate global download speed limiter is ebabled.'),
"alt-speed-time-begin": ('number', 5, None, None, None, 'Time when alternate speeds should be enabled. Minutes after midnight.'),
"alt-speed-time-enabled": ('boolean', 5, None, None, None, 'True if alternate speeds scheduling is enabled.'),
"alt-speed-time-end": ('number', 5, None, None, None, 'Time when alternate speeds should be disabled. Minutes after midnight.'),
"alt-speed-time-day": ('number', 5, None, None, None, 'Days alternate speeds scheduling is enabled.'),
"alt-speed-up": ('number', 5, None, None, None, 'Alternate session upload speed limit (in Kib/s)'),
"blocklist-enabled": ('boolean', 5, None, None, None, 'True when blocklist is enabled.'),
"blocklist-size": ('number', 5, None, None, None, 'Number of rules in the blocklist'),
"blocklist-url": ('string', 11, None, None, None, 'Location of the block list. Updated with blocklist-update.'),
"cache-size-mb": ('number', 10, None, None, None, 'The maximum size of the disk cache in MB'),
"config-dir": ('string', 8, None, None, None, 'location of transmissions configuration directory'),
"dht-enabled": ('boolean', 6, None, None, None, 'True if DHT enabled.'),
"download-dir": ('string', 1, None, None, None, 'The download directory.'),
"download-dir-free-space": ('number', 12, None, None, None, 'Free space in the download directory, in bytes'),
"download-queue-size": ('number', 14, None, None, None, 'Number of slots in the download queue.'),
"download-queue-enabled": ('boolean', 14, None, None, None, 'True if the download queue is enabled.'),
"encryption": ('string', 1, None, None, None, 'Encryption mode, one of ``required``, ``preferred`` or ``tolerated``.'),
"idle-seeding-limit": ('number', 10, None, None, None, 'Seed inactivity limit in minutes.'),
"idle-seeding-limit-enabled": ('boolean', 10, None, None, None, 'True if the seed activity limit is enabled.'),
"incomplete-dir": ('string', 7, None, None, None, 'The path to the directory for incomplete torrent transfer data.'),
"incomplete-dir-enabled": ('boolean', 7, None, None, None, 'True if the incomplete dir is enabled.'),
"lpd-enabled": ('boolean', 9, None, None, None, 'True if local peer discovery is enabled.'),
"peer-limit": ('number', 1, 5, None, 'peer-limit-global', 'Maximum number of peers.'),
"peer-limit-global": ('number', 5, None, 'peer-limit', None, 'Maximum number of peers.'),
"peer-limit-per-torrent": ('number', 5, None, None, None, 'Maximum number of peers per transfer.'),
"pex-allowed": ('boolean', 1, 5, None, 'pex-enabled', 'True if PEX is allowed.'),
"pex-enabled": ('boolean', 5, None, 'pex-allowed', None, 'True if PEX is enabled.'),
"port": ('number', 1, 5, None, 'peer-port', 'Peer port.'),
"peer-port": ('number', 5, None, 'port', None, 'Peer port.'),
"peer-port-random-on-start": ('boolean', 5, None, None, None, 'Enables randomized peer port on start of Transmission.'),
"port-forwarding-enabled": ('boolean', 1, None, None, None, 'True if port forwarding is enabled.'),
"queue-stalled-minutes": ('number', 14, None, None, None, 'Number of minutes of idle that marks a transfer as stalled.'),
"queue-stalled-enabled": ('boolean', 14, None, None, None, 'True if stalled tracking of transfers is enabled.'),
"rename-partial-files": ('boolean', 8, None, None, None, 'True if ".part" is appended to incomplete files'),
"rpc-version": ('number', 4, None, None, None, 'Transmission RPC API Version.'),
"rpc-version-minimum": ('number', 4, None, None, None, 'Minimum accepted RPC API Version.'),
"script-torrent-done-enabled": ('boolean', 9, None, None, None, 'True if the done script is enabled.'),
"script-torrent-done-filename": ('string', 9, None, None, None, 'Filename of the script to run when the transfer is done.'),
"seedRatioLimit": ('double', 5, None, None, None, 'Seed ratio limit. 1.0 means 1:1 download and upload ratio.'),
"seedRatioLimited": ('boolean', 5, None, None, None, 'True if seed ration limit is enabled.'),
"seed-queue-size": ('number', 14, None, None, None, 'Number of slots in the upload queue.'),
"seed-queue-enabled": ('boolean', 14, None, None, None, 'True if upload queue is enabled.'),
"speed-limit-down": ('number', 1, None, None, None, 'Download speed limit (in Kib/s).'),
"speed-limit-down-enabled": ('boolean', 1, None, None, None, 'True if the download speed is limited.'),
"speed-limit-up": ('number', 1, None, None, None, 'Upload speed limit (in Kib/s).'),
"speed-limit-up-enabled": ('boolean', 1, None, None, None, 'True if the upload speed is limited.'),
"start-added-torrents": ('boolean', 9, None, None, None, 'When true uploaded torrents will start right away.'),
"trash-original-torrent-files": ('boolean', 9, None, None, None, 'When true added .torrent files will be deleted.'),
'units': ('object', 10, None, None, None, 'An object containing units for size and speed.'),
'utp-enabled': ('boolean', 13, None, None, None, 'True if Micro Transport Protocol (UTP) is enabled.'),
"version": ('string', 3, None, None, None, 'Transmission version.'),
},
'set': {
"alt-speed-down": ('number', 5, None, None, None, 'Alternate session download speed limit (in Kib/s).'),
"alt-speed-enabled": ('boolean', 5, None, None, None, 'Enables alternate global download speed limiter.'),
"alt-speed-time-begin": ('number', 5, None, None, None, 'Time when alternate speeds should be enabled. Minutes after midnight.'),
"alt-speed-time-enabled": ('boolean', 5, None, None, None, 'Enables alternate speeds scheduling.'),
"alt-speed-time-end": ('number', 5, None, None, None, 'Time when alternate speeds should be disabled. Minutes after midnight.'),
"alt-speed-time-day": ('number', 5, None, None, None, 'Enables alternate speeds scheduling these days.'),
"alt-speed-up": ('number', 5, None, None, None, 'Alternate session upload speed limit (in Kib/s).'),
"blocklist-enabled": ('boolean', 5, None, None, None, 'Enables the block list'),
"blocklist-url": ('string', 11, None, None, None, 'Location of the block list. Updated with blocklist-update.'),
"cache-size-mb": ('number', 10, None, None, None, 'The maximum size of the disk cache in MB'),
"dht-enabled": ('boolean', 6, None, None, None, 'Enables DHT.'),
"download-dir": ('string', 1, None, None, None, 'Set the session download directory.'),
"download-queue-size": ('number', 14, None, None, None, 'Number of slots in the download queue.'),
"download-queue-enabled": ('boolean', 14, None, None, None, 'Enables download queue.'),
"encryption": ('string', 1, None, None, None, 'Set the session encryption mode, one of ``required``, ``preferred`` or ``tolerated``.'),
"idle-seeding-limit": ('number', 10, None, None, None, 'The default seed inactivity limit in minutes.'),
"idle-seeding-limit-enabled": ('boolean', 10, None, None, None, 'Enables the default seed inactivity limit'),
"incomplete-dir": ('string', 7, None, None, None, 'The path to the directory of incomplete transfer data.'),
"incomplete-dir-enabled": ('boolean', 7, None, None, None, 'Enables the incomplete transfer data directory. Otherwise data for incomplete transfers are stored in the download target.'),
"lpd-enabled": ('boolean', 9, None, None, None, 'Enables local peer discovery for public torrents.'),
"peer-limit": ('number', 1, 5, None, 'peer-limit-global', 'Maximum number of peers.'),
"peer-limit-global": ('number', 5, None, 'peer-limit', None, 'Maximum number of peers.'),
"peer-limit-per-torrent": ('number', 5, None, None, None, 'Maximum number of peers per transfer.'),
"pex-allowed": ('boolean', 1, 5, None, 'pex-enabled', 'Allowing PEX in public torrents.'),
"pex-enabled": ('boolean', 5, None, 'pex-allowed', None, 'Allowing PEX in public torrents.'),
"port": ('number', 1, 5, None, 'peer-port', 'Peer port.'),
"peer-port": ('number', 5, None, 'port', None, 'Peer port.'),
"peer-port-random-on-start": ('boolean', 5, None, None, None, 'Enables randomized peer port on start of Transmission.'),
"port-forwarding-enabled": ('boolean', 1, None, None, None, 'Enables port forwarding.'),
"rename-partial-files": ('boolean', 8, None, None, None, 'Appends ".part" to incomplete files'),
"queue-stalled-minutes": ('number', 14, None, None, None, 'Number of minutes of idle that marks a transfer as stalled.'),
"queue-stalled-enabled": ('boolean', 14, None, None, None, 'Enable tracking of stalled transfers.'),
"script-torrent-done-enabled": ('boolean', 9, None, None, None, 'Whether or not to call the "done" script.'),
"script-torrent-done-filename": ('string', 9, None, None, None, 'Filename of the script to run when the transfer is done.'),
"seed-queue-size": ('number', 14, None, None, None, 'Number of slots in the upload queue.'),
"seed-queue-enabled": ('boolean', 14, None, None, None, 'Enables upload queue.'),
"seedRatioLimit": ('double', 5, None, None, None, 'Seed ratio limit. 1.0 means 1:1 download and upload ratio.'),
"seedRatioLimited": ('boolean', 5, None, None, None, 'Enables seed ration limit.'),
"speed-limit-down": ('number', 1, None, None, None, 'Download speed limit (in Kib/s).'),
"speed-limit-down-enabled": ('boolean', 1, None, None, None, 'Enables download speed limiting.'),
"speed-limit-up": ('number', 1, None, None, None, 'Upload speed limit (in Kib/s).'),
"speed-limit-up-enabled": ('boolean', 1, None, None, None, 'Enables upload speed limiting.'),
"start-added-torrents": ('boolean', 9, None, None, None, 'Added torrents will be started right away.'),
"trash-original-torrent-files": ('boolean', 9, None, None, None, 'The .torrent file of added torrents will be deleted.'),
'utp-enabled': ('boolean', 13, None, None, None, 'Enables Micro Transport Protocol (UTP).'),
},
}
| 28,305 | Python | .py | 281 | 92.053381 | 201 | 0.564152 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,201 | utils.py | evilhero_mylar/lib/transmissionrpc/utils.py | # -*- coding: utf-8 -*-
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
import socket, datetime, logging
from collections import namedtuple
import transmissionrpc.constants as constants
from transmissionrpc.constants import LOGGER
from six import string_types, iteritems
UNITS = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']
def format_size(size):
"""
Format byte size into IEC prefixes, B, KiB, MiB ...
"""
size = float(size)
i = 0
while size >= 1024.0 and i < len(UNITS):
i += 1
size /= 1024.0
return (size, UNITS[i])
def format_speed(size):
"""
Format bytes per second speed into IEC prefixes, B/s, KiB/s, MiB/s ...
"""
(size, unit) = format_size(size)
return (size, unit + '/s')
def format_timedelta(delta):
"""
Format datetime.timedelta into <days> <hours>:<minutes>:<seconds>.
"""
minutes, seconds = divmod(delta.seconds, 60)
hours, minutes = divmod(minutes, 60)
return '%d %02d:%02d:%02d' % (delta.days, hours, minutes, seconds)
def format_timestamp(timestamp, utc=False):
"""
Format unix timestamp into ISO date format.
"""
if timestamp > 0:
if utc:
dt_timestamp = datetime.datetime.utcfromtimestamp(timestamp)
else:
dt_timestamp = datetime.datetime.fromtimestamp(timestamp)
return dt_timestamp.isoformat(' ')
else:
return '-'
class INetAddressError(Exception):
"""
Error parsing / generating a internet address.
"""
pass
def inet_address(address, default_port, default_address='localhost'):
"""
Parse internet address.
"""
addr = address.split(':')
if len(addr) == 1:
try:
port = int(addr[0])
addr = default_address
except ValueError:
addr = addr[0]
port = default_port
elif len(addr) == 2:
try:
port = int(addr[1])
except ValueError:
raise INetAddressError('Invalid address "%s".' % address)
if len(addr[0]) == 0:
addr = default_address
else:
addr = addr[0]
else:
raise INetAddressError('Invalid address "%s".' % address)
try:
socket.getaddrinfo(addr, port, socket.AF_INET, socket.SOCK_STREAM)
except socket.gaierror:
raise INetAddressError('Cannot look up address "%s".' % address)
return (addr, port)
def rpc_bool(arg):
"""
Convert between Python boolean and Transmission RPC boolean.
"""
if isinstance(arg, string_types):
try:
arg = bool(int(arg))
except ValueError:
arg = arg.lower() in ['true', 'yes']
return 1 if bool(arg) else 0
TR_TYPE_MAP = {
'number' : int,
'string' : str,
'double': float,
'boolean' : rpc_bool,
'array': list,
'object': dict
}
def make_python_name(name):
"""
Convert Transmission RPC name to python compatible name.
"""
return name.replace('-', '_')
def make_rpc_name(name):
"""
Convert python compatible name to Transmission RPC name.
"""
return name.replace('_', '-')
def argument_value_convert(method, argument, value, rpc_version):
"""
Check and fix Transmission RPC issues with regards to methods, arguments and values.
"""
if method in ('torrent-add', 'torrent-get', 'torrent-set'):
args = constants.TORRENT_ARGS[method[-3:]]
elif method in ('session-get', 'session-set'):
args = constants.SESSION_ARGS[method[-3:]]
else:
return ValueError('Method "%s" not supported' % (method))
if argument in args:
info = args[argument]
invalid_version = True
while invalid_version:
invalid_version = False
replacement = None
if rpc_version < info[1]:
invalid_version = True
replacement = info[3]
if info[2] and info[2] <= rpc_version:
invalid_version = True
replacement = info[4]
if invalid_version:
if replacement:
LOGGER.warning(
'Replacing requested argument "%s" with "%s".'
% (argument, replacement))
argument = replacement
info = args[argument]
else:
raise ValueError(
'Method "%s" Argument "%s" does not exist in version %d.'
% (method, argument, rpc_version))
return (argument, TR_TYPE_MAP[info[0]](value))
else:
raise ValueError('Argument "%s" does not exists for method "%s".',
(argument, method))
def get_arguments(method, rpc_version):
"""
Get arguments for method in specified Transmission RPC version.
"""
if method in ('torrent-add', 'torrent-get', 'torrent-set'):
args = constants.TORRENT_ARGS[method[-3:]]
elif method in ('session-get', 'session-set'):
args = constants.SESSION_ARGS[method[-3:]]
else:
return ValueError('Method "%s" not supported' % (method))
accessible = []
for argument, info in iteritems(args):
valid_version = True
if rpc_version < info[1]:
valid_version = False
if info[2] and info[2] <= rpc_version:
valid_version = False
if valid_version:
accessible.append(argument)
return accessible
def add_stdout_logger(level='debug'):
"""
Add a stdout target for the transmissionrpc logging.
"""
levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR}
trpc_logger = logging.getLogger('transmissionrpc')
loghandler = logging.StreamHandler()
if level in list(levels.keys()):
loglevel = levels[level]
trpc_logger.setLevel(loglevel)
loghandler.setLevel(loglevel)
trpc_logger.addHandler(loghandler)
def add_file_logger(filepath, level='debug'):
"""
Add a stdout target for the transmissionrpc logging.
"""
levels = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR}
trpc_logger = logging.getLogger('transmissionrpc')
loghandler = logging.FileHandler(filepath, encoding='utf-8')
if level in list(levels.keys()):
loglevel = levels[level]
trpc_logger.setLevel(loglevel)
loghandler.setLevel(loglevel)
trpc_logger.addHandler(loghandler)
Field = namedtuple('Field', ['value', 'dirty'])
| 6,811 | Python | .py | 187 | 27.807487 | 112 | 0.590371 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,202 | __init__.py | evilhero_mylar/lib/transmissionrpc/__init__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
from transmissionrpc.constants import DEFAULT_PORT, DEFAULT_TIMEOUT, PRIORITY, RATIO_LIMIT, LOGGER
from transmissionrpc.error import TransmissionError, HTTPHandlerError
from transmissionrpc.httphandler import HTTPHandler, DefaultHTTPHandler
from transmissionrpc.torrent import Torrent
from transmissionrpc.session import Session
from transmissionrpc.client import Client
from transmissionrpc.utils import add_stdout_logger, add_file_logger
__author__ = 'Erik Svensson <erik.public@gmail.com>'
__version_major__ = 0
__version_minor__ = 11
__version__ = '{0}.{1}'.format(__version_major__, __version_minor__)
__copyright__ = 'Copyright (c) 2008-2013 Erik Svensson'
__license__ = 'MIT'
| 844 | Python | .py | 16 | 50.5 | 99 | 0.751214 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,203 | torrent.py | evilhero_mylar/lib/transmissionrpc/torrent.py | # -*- coding: utf-8 -*-
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
import sys, datetime
from transmissionrpc.constants import PRIORITY, RATIO_LIMIT, IDLE_LIMIT
from transmissionrpc.utils import Field, format_timedelta
from six import integer_types, string_types, text_type, iteritems
def get_status_old(code):
"""Get the torrent status using old status codes"""
mapping = {
(1<<0): 'check pending',
(1<<1): 'checking',
(1<<2): 'downloading',
(1<<3): 'seeding',
(1<<4): 'stopped',
}
return mapping[code]
def get_status_new(code):
"""Get the torrent status using new status codes"""
mapping = {
0: 'stopped',
1: 'check pending',
2: 'checking',
3: 'download pending',
4: 'downloading',
5: 'seed pending',
6: 'seeding',
}
return mapping[code]
class Torrent(object):
"""
Torrent is a class holding the data received from Transmission regarding a bittorrent transfer.
All fetched torrent fields are accessible through this class using attributes.
This class has a few convenience properties using the torrent data.
"""
def __init__(self, client, fields):
if 'id' not in fields:
raise ValueError('Torrent requires an id')
self._fields = {}
self._update_fields(fields)
self._incoming_pending = False
self._outgoing_pending = False
self._client = client
def _get_name_string(self, codec=None):
"""Get the name"""
if codec is None:
codec = sys.getdefaultencoding()
name = None
# try to find name
if 'name' in self._fields:
name = self._fields['name'].value
# if name is unicode, try to decode
if isinstance(name, text_type):
try:
name = name.encode(codec)
except UnicodeError:
name = None
return name
def __repr__(self):
tid = self._fields['id'].value
name = self._get_name_string()
if isinstance(name, str):
return '<Torrent %d \"%s\">' % (tid, name)
else:
return '<Torrent %d>' % (tid)
def __str__(self):
name = self._get_name_string()
if isinstance(name, str):
return 'Torrent \"%s\"' % (name)
else:
return 'Torrent'
def __copy__(self):
return Torrent(self._client, self._fields)
def __getattr__(self, name):
try:
return self._fields[name].value
except KeyError:
raise AttributeError('No attribute %s' % name)
def _rpc_version(self):
"""Get the Transmission RPC API version."""
if self._client:
return self._client.rpc_version
return 2
def _dirty_fields(self):
"""Enumerate changed fields"""
outgoing_keys = ['bandwidthPriority', 'downloadLimit', 'downloadLimited', 'peer_limit', 'queuePosition'
, 'seedIdleLimit', 'seedIdleMode', 'seedRatioLimit', 'seedRatioMode', 'uploadLimit', 'uploadLimited']
fields = []
for key in outgoing_keys:
if key in self._fields and self._fields[key].dirty:
fields.append(key)
return fields
def _push(self):
"""Push changed fields to the server"""
dirty = self._dirty_fields()
args = {}
for key in dirty:
args[key] = self._fields[key].value
self._fields[key] = self._fields[key]._replace(dirty=False)
if len(args) > 0:
self._client.change_torrent(self.id, **args)
def _update_fields(self, other):
"""
Update the torrent data from a Transmission JSON-RPC arguments dictionary
"""
fields = None
if isinstance(other, dict):
for key, value in iteritems(other):
self._fields[key.replace('-', '_')] = Field(value, False)
elif isinstance(other, Torrent):
for key in list(other._fields.keys()):
self._fields[key] = Field(other._fields[key].value, False)
else:
raise ValueError('Cannot update with supplied data')
self._incoming_pending = False
def _status(self):
"""Get the torrent status"""
code = self._fields['status'].value
if self._rpc_version() >= 14:
return get_status_new(code)
else:
return get_status_old(code)
def files(self):
"""
Get list of files for this torrent.
This function returns a dictionary with file information for each file.
The file information is has following fields:
::
{
<file id>: {
'name': <file name>,
'size': <file size in bytes>,
'completed': <bytes completed>,
'priority': <priority ('high'|'normal'|'low')>,
'selected': <selected for download>
}
...
}
"""
result = {}
if 'files' in self._fields:
files = self._fields['files'].value
indices = range(len(files))
priorities = self._fields['priorities'].value
wanted = self._fields['wanted'].value
for item in zip(indices, files, priorities, wanted):
selected = True if item[3] else False
priority = PRIORITY[item[2]]
result[item[0]] = {
'selected': selected,
'priority': priority,
'size': item[1]['length'],
'name': item[1]['name'],
'completed': item[1]['bytesCompleted']}
return result
@property
def status(self):
"""
Returns the torrent status. Is either one of 'check pending', 'checking',
'downloading', 'seeding' or 'stopped'. The first two is related to
verification.
"""
return self._status()
@property
def progress(self):
"""Get the download progress in percent."""
try:
size = self._fields['sizeWhenDone'].value
left = self._fields['leftUntilDone'].value
return 100.0 * (size - left) / float(size)
except ZeroDivisionError:
return 0.0
@property
def ratio(self):
"""Get the upload/download ratio."""
return float(self._fields['uploadRatio'].value)
@property
def eta(self):
"""Get the "eta" as datetime.timedelta."""
eta = self._fields['eta'].value
if eta >= 0:
return datetime.timedelta(seconds=eta)
else:
raise ValueError('eta not valid')
@property
def date_active(self):
"""Get the attribute "activityDate" as datetime.datetime."""
return datetime.datetime.fromtimestamp(self._fields['activityDate'].value)
@property
def date_added(self):
"""Get the attribute "addedDate" as datetime.datetime."""
return datetime.datetime.fromtimestamp(self._fields['addedDate'].value)
@property
def date_started(self):
"""Get the attribute "startDate" as datetime.datetime."""
return datetime.datetime.fromtimestamp(self._fields['startDate'].value)
@property
def date_done(self):
"""Get the attribute "doneDate" as datetime.datetime."""
return datetime.datetime.fromtimestamp(self._fields['doneDate'].value)
def format_eta(self):
"""
Returns the attribute *eta* formatted as a string.
* If eta is -1 the result is 'not available'
* If eta is -2 the result is 'unknown'
* Otherwise eta is formatted as <days> <hours>:<minutes>:<seconds>.
"""
eta = self._fields['eta'].value
if eta == -1:
return 'not available'
elif eta == -2:
return 'unknown'
else:
return format_timedelta(self.eta)
def _get_download_limit(self):
"""
Get the download limit.
Can be a number or None.
"""
if self._fields['downloadLimited'].value:
return self._fields['downloadLimit'].value
else:
return None
def _set_download_limit(self, limit):
"""
Get the download limit.
Can be a number, 'session' or None.
"""
if isinstance(limit, integer_types):
self._fields['downloadLimited'] = Field(True, True)
self._fields['downloadLimit'] = Field(limit, True)
self._push()
elif limit == None:
self._fields['downloadLimited'] = Field(False, True)
self._push()
else:
raise ValueError("Not a valid limit")
download_limit = property(_get_download_limit, _set_download_limit, None, "Download limit in Kbps or None. This is a mutator.")
def _get_peer_limit(self):
"""
Get the peer limit.
"""
return self._fields['peer_limit'].value
def _set_peer_limit(self, limit):
"""
Set the peer limit.
"""
if isinstance(limit, integer_types):
self._fields['peer_limit'] = Field(limit, True)
self._push()
else:
raise ValueError("Not a valid limit")
peer_limit = property(_get_peer_limit, _set_peer_limit, None, "Peer limit. This is a mutator.")
def _get_priority(self):
"""
Get the priority as string.
Can be one of 'low', 'normal', 'high'.
"""
return PRIORITY[self._fields['bandwidthPriority'].value]
def _set_priority(self, priority):
"""
Set the priority as string.
Can be one of 'low', 'normal', 'high'.
"""
if isinstance(priority, string_types):
self._fields['bandwidthPriority'] = Field(PRIORITY[priority], True)
self._push()
priority = property(_get_priority, _set_priority, None
, "Bandwidth priority as string. Can be one of 'low', 'normal', 'high'. This is a mutator.")
def _get_seed_idle_limit(self):
"""
Get the seed idle limit in minutes.
"""
return self._fields['seedIdleLimit'].value
def _set_seed_idle_limit(self, limit):
"""
Set the seed idle limit in minutes.
"""
if isinstance(limit, integer_types):
self._fields['seedIdleLimit'] = Field(limit, True)
self._push()
else:
raise ValueError("Not a valid limit")
seed_idle_limit = property(_get_seed_idle_limit, _set_seed_idle_limit, None
, "Torrent seed idle limit in minutes. Also see seed_idle_mode. This is a mutator.")
def _get_seed_idle_mode(self):
"""
Get the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'.
"""
return IDLE_LIMIT[self._fields['seedIdleMode'].value]
def _set_seed_idle_mode(self, mode):
"""
Set the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'.
"""
if isinstance(mode, str):
self._fields['seedIdleMode'] = Field(IDLE_LIMIT[mode], True)
self._push()
else:
raise ValueError("Not a valid limit")
seed_idle_mode = property(_get_seed_idle_mode, _set_seed_idle_mode, None,
"""
Seed idle mode as string. Can be one of 'global', 'single' or 'unlimited'.
* global, use session seed idle limit.
* single, use torrent seed idle limit. See seed_idle_limit.
* unlimited, no seed idle limit.
This is a mutator.
"""
)
def _get_seed_ratio_limit(self):
"""
Get the seed ratio limit as float.
"""
return float(self._fields['seedRatioLimit'].value)
def _set_seed_ratio_limit(self, limit):
"""
Set the seed ratio limit as float.
"""
if isinstance(limit, (integer_types, float)) and limit >= 0.0:
self._fields['seedRatioLimit'] = Field(float(limit), True)
self._push()
else:
raise ValueError("Not a valid limit")
seed_ratio_limit = property(_get_seed_ratio_limit, _set_seed_ratio_limit, None
, "Torrent seed ratio limit as float. Also see seed_ratio_mode. This is a mutator.")
def _get_seed_ratio_mode(self):
"""
Get the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'.
"""
return RATIO_LIMIT[self._fields['seedRatioMode'].value]
def _set_seed_ratio_mode(self, mode):
"""
Set the seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'.
"""
if isinstance(mode, str):
self._fields['seedRatioMode'] = Field(RATIO_LIMIT[mode], True)
self._push()
else:
raise ValueError("Not a valid limit")
seed_ratio_mode = property(_get_seed_ratio_mode, _set_seed_ratio_mode, None,
"""
Seed ratio mode as string. Can be one of 'global', 'single' or 'unlimited'.
* global, use session seed ratio limit.
* single, use torrent seed ratio limit. See seed_ratio_limit.
* unlimited, no seed ratio limit.
This is a mutator.
"""
)
def _get_upload_limit(self):
"""
Get the upload limit.
Can be a number or None.
"""
if self._fields['uploadLimited'].value:
return self._fields['uploadLimit'].value
else:
return None
def _set_upload_limit(self, limit):
"""
Set the upload limit.
Can be a number, 'session' or None.
"""
if isinstance(limit, integer_types):
self._fields['uploadLimited'] = Field(True, True)
self._fields['uploadLimit'] = Field(limit, True)
self._push()
elif limit == None:
self._fields['uploadLimited'] = Field(False, True)
self._push()
else:
raise ValueError("Not a valid limit")
upload_limit = property(_get_upload_limit, _set_upload_limit, None, "Upload limit in Kbps or None. This is a mutator.")
def _get_queue_position(self):
"""Get the queue position for this torrent."""
if self._rpc_version() >= 14:
return self._fields['queuePosition'].value
else:
return 0
def _set_queue_position(self, position):
"""Set the queue position for this torrent."""
if self._rpc_version() >= 14:
if isinstance(position, integer_types):
self._fields['queuePosition'] = Field(position, True)
self._push()
else:
raise ValueError("Not a valid position")
else:
pass
queue_position = property(_get_queue_position, _set_queue_position, None, "Queue position")
def update(self, timeout=None):
"""Update the torrent information."""
self._push()
torrent = self._client.get_torrent(self.id, timeout=timeout)
self._update_fields(torrent)
def start(self, bypass_queue=False, timeout=None):
"""
Start the torrent.
"""
self._incoming_pending = True
self._client.start_torrent(self.id, bypass_queue=bypass_queue, timeout=timeout)
def stop(self, timeout=None):
"""Stop the torrent."""
self._incoming_pending = True
self._client.stop_torrent(self.id, timeout=timeout)
def move_data(self, location, timeout=None):
"""Move torrent data to location."""
self._incoming_pending = True
self._client.move_torrent_data(self.id, location, timeout=timeout)
def locate_data(self, location, timeout=None):
"""Locate torrent data at location."""
self._incoming_pending = True
self._client.locate_torrent_data(self.id, location, timeout=timeout)
| 16,544 | Python | .py | 411 | 29.527981 | 132 | 0.563121 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,204 | httphandler.py | evilhero_mylar/lib/transmissionrpc/httphandler.py | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
import sys
from transmissionrpc.error import HTTPHandlerError
from six import PY3
if PY3:
from urllib.request import Request, build_opener, \
HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, HTTPDigestAuthHandler
from urllib.error import HTTPError, URLError
from http.client import BadStatusLine
else:
from urllib2 import Request, build_opener, \
HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, HTTPDigestAuthHandler
from urllib2 import HTTPError, URLError
from httplib import BadStatusLine
class HTTPHandler(object):
"""
Prototype for HTTP handling.
"""
def set_authentication(self, uri, login, password):
"""
Transmission use basic authentication in earlier versions and digest
authentication in later versions.
* uri, the authentication realm URI.
* login, the authentication login.
* password, the authentication password.
"""
raise NotImplementedError("Bad HTTPHandler, failed to implement set_authentication.")
def request(self, url, query, headers, timeout):
"""
Implement a HTTP POST request here.
* url, The URL to request.
* query, The query data to send. This is a JSON data string.
* headers, a dictionary of headers to send.
* timeout, requested request timeout in seconds.
"""
raise NotImplementedError("Bad HTTPHandler, failed to implement request.")
class DefaultHTTPHandler(HTTPHandler):
"""
The default HTTP handler provided with transmissionrpc.
"""
def __init__(self):
HTTPHandler.__init__(self)
self.http_opener = build_opener()
def set_authentication(self, uri, login, password):
password_manager = HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(realm=None, uri=uri, user=login, passwd=password)
self.http_opener = build_opener(HTTPBasicAuthHandler(password_manager), HTTPDigestAuthHandler(password_manager))
def request(self, url, query, headers, timeout):
request = Request(url, query.encode('utf-8'), headers)
try:
if (sys.version_info[0] == 2 and sys.version_info[1] > 5) or sys.version_info[0] > 2:
response = self.http_opener.open(request, timeout=timeout)
else:
response = self.http_opener.open(request)
except HTTPError as error:
if error.fp is None:
raise HTTPHandlerError(error.filename, error.code, error.msg, dict(error.hdrs))
else:
raise HTTPHandlerError(error.filename, error.code, error.msg, dict(error.hdrs), error.read())
except URLError as error:
# urllib2.URLError documentation is horrendous!
# Try to get the tuple arguments of URLError
if hasattr(error.reason, 'args') and isinstance(error.reason.args, tuple) and len(error.reason.args) == 2:
raise HTTPHandlerError(httpcode=error.reason.args[0], httpmsg=error.reason.args[1])
else:
raise HTTPHandlerError(httpmsg='urllib2.URLError: %s' % (error.reason))
except BadStatusLine as error:
raise HTTPHandlerError(httpmsg='httplib.BadStatusLine: %s' % (error.line))
return response.read().decode('utf-8')
| 3,550 | Python | .py | 71 | 40.492958 | 121 | 0.667342 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,205 | session.py | evilhero_mylar/lib/transmissionrpc/session.py | # -*- coding: utf-8 -*-
# Copyright (c) 2008-2013 Erik Svensson <erik.public@gmail.com>
# Licensed under the MIT license.
from transmissionrpc.utils import Field
from six import iteritems, integer_types
class Session(object):
"""
Session is a class holding the session data for a Transmission daemon.
Access the session field can be done through attributes.
The attributes available are the same as the session arguments in the
Transmission RPC specification, but with underscore instead of hyphen.
``download-dir`` -> ``download_dir``.
"""
def __init__(self, client=None, fields=None):
self._client = client
self._fields = {}
if fields is not None:
self._update_fields(fields)
def __getattr__(self, name):
try:
return self._fields[name].value
except KeyError:
raise AttributeError('No attribute %s' % name)
def __str__(self):
text = ''
for key in sorted(self._fields.keys()):
text += "% 32s: %s\n" % (key[-32:], self._fields[key].value)
return text
def _update_fields(self, other):
"""
Update the session data from a Transmission JSON-RPC arguments dictionary
"""
if isinstance(other, dict):
for key, value in iteritems(other):
self._fields[key.replace('-', '_')] = Field(value, False)
elif isinstance(other, Session):
for key in list(other._fields.keys()):
self._fields[key] = Field(other._fields[key].value, False)
else:
raise ValueError('Cannot update with supplied data')
def _dirty_fields(self):
"""Enumerate changed fields"""
outgoing_keys = ['peer_port', 'pex_enabled']
fields = []
for key in outgoing_keys:
if key in self._fields and self._fields[key].dirty:
fields.append(key)
return fields
def _push(self):
"""Push changed fields to the server"""
dirty = self._dirty_fields()
args = {}
for key in dirty:
args[key] = self._fields[key].value
self._fields[key] = self._fields[key]._replace(dirty=False)
if len(args) > 0:
self._client.set_session(**args)
def update(self, timeout=None):
"""Update the session information."""
self._push()
session = self._client.get_session(timeout=timeout)
self._update_fields(session)
session = self._client.session_stats(timeout=timeout)
self._update_fields(session)
def from_request(self, data):
"""Update the session information."""
self._update_fields(data)
def _get_peer_port(self):
"""
Get the peer port.
"""
return self._fields['peer_port'].value
def _set_peer_port(self, port):
"""
Set the peer port.
"""
if isinstance(port, integer_types):
self._fields['peer_port'] = Field(port, True)
self._push()
else:
raise ValueError("Not a valid limit")
peer_port = property(_get_peer_port, _set_peer_port, None, "Peer port. This is a mutator.")
def _get_pex_enabled(self):
"""Is peer exchange enabled?"""
return self._fields['pex_enabled'].value
def _set_pex_enabled(self, enabled):
"""Enable/disable peer exchange."""
if isinstance(enabled, bool):
self._fields['pex_enabled'] = Field(enabled, True)
self._push()
else:
raise TypeError("Not a valid type")
pex_enabled = property(_get_pex_enabled, _set_pex_enabled, None, "Enable peer exchange. This is a mutator.")
| 3,837 | Python | .py | 93 | 31.301075 | 113 | 0.583333 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,206 | __init__.py | evilhero_mylar/lib/funcsigs/__init__.py | # Copyright 2001-2013 Python Software Foundation; All Rights Reserved
"""Function signature objects for callables
Back port of Python 3.3's function signature tools from the inspect module,
modified to be compatible with Python 2.6, 2.7 and 3.3+.
"""
from __future__ import absolute_import, division, print_function
import itertools
import functools
import re
import types
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
from funcsigs.version import __version__
__all__ = ['BoundArguments', 'Parameter', 'Signature', 'signature']
_WrapperDescriptor = type(type.__call__)
_MethodWrapper = type(all.__call__)
_NonUserDefinedCallables = (_WrapperDescriptor,
_MethodWrapper,
types.BuiltinFunctionType)
def formatannotation(annotation, base_module=None):
if isinstance(annotation, type):
if annotation.__module__ in ('builtins', '__builtin__', base_module):
return annotation.__name__
return annotation.__module__+'.'+annotation.__name__
return repr(annotation)
def _get_user_defined_method(cls, method_name, *nested):
try:
if cls is type:
return
meth = getattr(cls, method_name)
for name in nested:
meth = getattr(meth, name, meth)
except AttributeError:
return
else:
if not isinstance(meth, _NonUserDefinedCallables):
# Once '__signature__' will be added to 'C'-level
# callables, this check won't be necessary
return meth
def signature(obj):
'''Get a signature object for the passed callable.'''
if not callable(obj):
raise TypeError('{0!r} is not a callable object'.format(obj))
if isinstance(obj, types.MethodType):
sig = signature(obj.__func__)
if obj.__self__ is None:
# Unbound method - preserve as-is.
return sig
else:
# Bound method. Eat self - if we can.
params = tuple(sig.parameters.values())
if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
raise ValueError('invalid method signature')
kind = params[0].kind
if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
# Drop first parameter:
# '(p1, p2[, ...])' -> '(p2[, ...])'
params = params[1:]
else:
if kind is not _VAR_POSITIONAL:
# Unless we add a new parameter type we never
# get here
raise ValueError('invalid argument type')
# It's a var-positional parameter.
# Do nothing. '(*args[, ...])' -> '(*args[, ...])'
return sig.replace(parameters=params)
try:
sig = obj.__signature__
except AttributeError:
pass
else:
if sig is not None:
return sig
try:
# Was this function wrapped by a decorator?
wrapped = obj.__wrapped__
except AttributeError:
pass
else:
return signature(wrapped)
if isinstance(obj, types.FunctionType):
return Signature.from_function(obj)
if isinstance(obj, functools.partial):
sig = signature(obj.func)
new_params = OrderedDict(sig.parameters.items())
partial_args = obj.args or ()
partial_keywords = obj.keywords or {}
try:
ba = sig.bind_partial(*partial_args, **partial_keywords)
except TypeError as ex:
msg = 'partial object {0!r} has incorrect arguments'.format(obj)
raise ValueError(msg)
for arg_name, arg_value in ba.arguments.items():
param = new_params[arg_name]
if arg_name in partial_keywords:
# We set a new default value, because the following code
# is correct:
#
# >>> def foo(a): print(a)
# >>> print(partial(partial(foo, a=10), a=20)())
# 20
# >>> print(partial(partial(foo, a=10), a=20)(a=30))
# 30
#
# So, with 'partial' objects, passing a keyword argument is
# like setting a new default value for the corresponding
# parameter
#
# We also mark this parameter with '_partial_kwarg'
# flag. Later, in '_bind', the 'default' value of this
# parameter will be added to 'kwargs', to simulate
# the 'functools.partial' real call.
new_params[arg_name] = param.replace(default=arg_value,
_partial_kwarg=True)
elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
not param._partial_kwarg):
new_params.pop(arg_name)
return sig.replace(parameters=new_params.values())
sig = None
if isinstance(obj, type):
# obj is a class or a metaclass
# First, let's see if it has an overloaded __call__ defined
# in its metaclass
call = _get_user_defined_method(type(obj), '__call__')
if call is not None:
sig = signature(call)
else:
# Now we check if the 'obj' class has a '__new__' method
new = _get_user_defined_method(obj, '__new__')
if new is not None:
sig = signature(new)
else:
# Finally, we should have at least __init__ implemented
init = _get_user_defined_method(obj, '__init__')
if init is not None:
sig = signature(init)
elif not isinstance(obj, _NonUserDefinedCallables):
# An object with __call__
# We also check that the 'obj' is not an instance of
# _WrapperDescriptor or _MethodWrapper to avoid
# infinite recursion (and even potential segfault)
call = _get_user_defined_method(type(obj), '__call__', 'im_func')
if call is not None:
sig = signature(call)
if sig is not None:
# For classes and objects we skip the first parameter of their
# __call__, __new__, or __init__ methods
return sig.replace(parameters=tuple(sig.parameters.values())[1:])
if isinstance(obj, types.BuiltinFunctionType):
# Raise a nicer error message for builtins
msg = 'no signature found for builtin function {0!r}'.format(obj)
raise ValueError(msg)
raise ValueError('callable {0!r} is not supported by signature'.format(obj))
class _void(object):
'''A private marker - used in Parameter & Signature'''
class _empty(object):
pass
class _ParameterKind(int):
def __new__(self, *args, **kwargs):
obj = int.__new__(self, *args)
obj._name = kwargs['name']
return obj
def __str__(self):
return self._name
def __repr__(self):
return '<_ParameterKind: {0!r}>'.format(self._name)
_POSITIONAL_ONLY = _ParameterKind(0, name='POSITIONAL_ONLY')
_POSITIONAL_OR_KEYWORD = _ParameterKind(1, name='POSITIONAL_OR_KEYWORD')
_VAR_POSITIONAL = _ParameterKind(2, name='VAR_POSITIONAL')
_KEYWORD_ONLY = _ParameterKind(3, name='KEYWORD_ONLY')
_VAR_KEYWORD = _ParameterKind(4, name='VAR_KEYWORD')
class Parameter(object):
'''Represents a parameter in a function signature.
Has the following public attributes:
* name : str
The name of the parameter as a string.
* default : object
The default value for the parameter if specified. If the
parameter has no default value, this attribute is not set.
* annotation
The annotation for the parameter if specified. If the
parameter has no annotation, this attribute is not set.
* kind : str
Describes how argument values are bound to the parameter.
Possible values: `Parameter.POSITIONAL_ONLY`,
`Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
`Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
'''
__slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
POSITIONAL_ONLY = _POSITIONAL_ONLY
POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
VAR_POSITIONAL = _VAR_POSITIONAL
KEYWORD_ONLY = _KEYWORD_ONLY
VAR_KEYWORD = _VAR_KEYWORD
empty = _empty
def __init__(self, name, kind, default=_empty, annotation=_empty,
_partial_kwarg=False):
if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
_VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
raise ValueError("invalid value for 'Parameter.kind' attribute")
self._kind = kind
if default is not _empty:
if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
msg = '{0} parameters cannot have default values'.format(kind)
raise ValueError(msg)
self._default = default
self._annotation = annotation
if name is None:
if kind != _POSITIONAL_ONLY:
raise ValueError("None is not a valid name for a "
"non-positional-only parameter")
self._name = name
else:
name = str(name)
if kind != _POSITIONAL_ONLY and not re.match(r'[a-z_]\w*$', name, re.I):
msg = '{0!r} is not a valid parameter name'.format(name)
raise ValueError(msg)
self._name = name
self._partial_kwarg = _partial_kwarg
@property
def name(self):
return self._name
@property
def default(self):
return self._default
@property
def annotation(self):
return self._annotation
@property
def kind(self):
return self._kind
def replace(self, name=_void, kind=_void, annotation=_void,
default=_void, _partial_kwarg=_void):
'''Creates a customized copy of the Parameter.'''
if name is _void:
name = self._name
if kind is _void:
kind = self._kind
if annotation is _void:
annotation = self._annotation
if default is _void:
default = self._default
if _partial_kwarg is _void:
_partial_kwarg = self._partial_kwarg
return type(self)(name, kind, default=default, annotation=annotation,
_partial_kwarg=_partial_kwarg)
def __str__(self):
kind = self.kind
formatted = self._name
if kind == _POSITIONAL_ONLY:
if formatted is None:
formatted = ''
formatted = '<{0}>'.format(formatted)
# Add annotation and default value
if self._annotation is not _empty:
formatted = '{0}:{1}'.format(formatted,
formatannotation(self._annotation))
if self._default is not _empty:
formatted = '{0}={1}'.format(formatted, repr(self._default))
if kind == _VAR_POSITIONAL:
formatted = '*' + formatted
elif kind == _VAR_KEYWORD:
formatted = '**' + formatted
return formatted
def __repr__(self):
return '<{0} at {1:#x} {2!r}>'.format(self.__class__.__name__,
id(self), self.name)
def __hash__(self):
msg = "unhashable type: '{0}'".format(self.__class__.__name__)
raise TypeError(msg)
def __eq__(self, other):
return (issubclass(other.__class__, Parameter) and
self._name == other._name and
self._kind == other._kind and
self._default == other._default and
self._annotation == other._annotation)
def __ne__(self, other):
return not self.__eq__(other)
class BoundArguments(object):
'''Result of `Signature.bind` call. Holds the mapping of arguments
to the function's parameters.
Has the following public attributes:
* arguments : OrderedDict
An ordered mutable mapping of parameters' names to arguments' values.
Does not contain arguments' default values.
* signature : Signature
The Signature object that created this instance.
* args : tuple
Tuple of positional arguments values.
* kwargs : dict
Dict of keyword arguments values.
'''
def __init__(self, signature, arguments):
self.arguments = arguments
self._signature = signature
@property
def signature(self):
return self._signature
@property
def args(self):
args = []
for param_name, param in self._signature.parameters.items():
if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
param._partial_kwarg):
# Keyword arguments mapped by 'functools.partial'
# (Parameter._partial_kwarg is True) are mapped
# in 'BoundArguments.kwargs', along with VAR_KEYWORD &
# KEYWORD_ONLY
break
try:
arg = self.arguments[param_name]
except KeyError:
# We're done here. Other arguments
# will be mapped in 'BoundArguments.kwargs'
break
else:
if param.kind == _VAR_POSITIONAL:
# *args
args.extend(arg)
else:
# plain argument
args.append(arg)
return tuple(args)
@property
def kwargs(self):
kwargs = {}
kwargs_started = False
for param_name, param in self._signature.parameters.items():
if not kwargs_started:
if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
param._partial_kwarg):
kwargs_started = True
else:
if param_name not in self.arguments:
kwargs_started = True
continue
if not kwargs_started:
continue
try:
arg = self.arguments[param_name]
except KeyError:
pass
else:
if param.kind == _VAR_KEYWORD:
# **kwargs
kwargs.update(arg)
else:
# plain keyword argument
kwargs[param_name] = arg
return kwargs
def __hash__(self):
msg = "unhashable type: '{0}'".format(self.__class__.__name__)
raise TypeError(msg)
def __eq__(self, other):
return (issubclass(other.__class__, BoundArguments) and
self.signature == other.signature and
self.arguments == other.arguments)
def __ne__(self, other):
return not self.__eq__(other)
class Signature(object):
'''A Signature object represents the overall signature of a function.
It stores a Parameter object for each parameter accepted by the
function, as well as information specific to the function itself.
A Signature object has the following public attributes and methods:
* parameters : OrderedDict
An ordered mapping of parameters' names to the corresponding
Parameter objects (keyword-only arguments are in the same order
as listed in `code.co_varnames`).
* return_annotation : object
The annotation for the return type of the function if specified.
If the function has no annotation for its return type, this
attribute is not set.
* bind(*args, **kwargs) -> BoundArguments
Creates a mapping from positional and keyword arguments to
parameters.
* bind_partial(*args, **kwargs) -> BoundArguments
Creates a partial mapping from positional and keyword arguments
to parameters (simulating 'functools.partial' behavior.)
'''
__slots__ = ('_return_annotation', '_parameters')
_parameter_cls = Parameter
_bound_arguments_cls = BoundArguments
empty = _empty
def __init__(self, parameters=None, return_annotation=_empty,
__validate_parameters__=True):
'''Constructs Signature from the given list of Parameter
objects and 'return_annotation'. All arguments are optional.
'''
if parameters is None:
params = OrderedDict()
else:
if __validate_parameters__:
params = OrderedDict()
top_kind = _POSITIONAL_ONLY
for idx, param in enumerate(parameters):
kind = param.kind
if kind < top_kind:
msg = 'wrong parameter order: {0} before {1}'
msg = msg.format(top_kind, param.kind)
raise ValueError(msg)
else:
top_kind = kind
name = param.name
if name is None:
name = str(idx)
param = param.replace(name=name)
if name in params:
msg = 'duplicate parameter name: {0!r}'.format(name)
raise ValueError(msg)
params[name] = param
else:
params = OrderedDict(((param.name, param)
for param in parameters))
self._parameters = params
self._return_annotation = return_annotation
@classmethod
def from_function(cls, func):
'''Constructs Signature for the given python function'''
if not isinstance(func, types.FunctionType):
raise TypeError('{0!r} is not a Python function'.format(func))
Parameter = cls._parameter_cls
# Parameter information.
func_code = func.__code__
pos_count = func_code.co_argcount
arg_names = func_code.co_varnames
positional = tuple(arg_names[:pos_count])
keyword_only_count = getattr(func_code, 'co_kwonlyargcount', 0)
keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
annotations = getattr(func, '__annotations__', {})
defaults = func.__defaults__
kwdefaults = getattr(func, '__kwdefaults__', None)
if defaults:
pos_default_count = len(defaults)
else:
pos_default_count = 0
parameters = []
# Non-keyword-only parameters w/o defaults.
non_default_count = pos_count - pos_default_count
for name in positional[:non_default_count]:
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_POSITIONAL_OR_KEYWORD))
# ... w/ defaults.
for offset, name in enumerate(positional[non_default_count:]):
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_POSITIONAL_OR_KEYWORD,
default=defaults[offset]))
# *args
if func_code.co_flags & 0x04:
name = arg_names[pos_count + keyword_only_count]
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_VAR_POSITIONAL))
# Keyword-only parameters.
for name in keyword_only:
default = _empty
if kwdefaults is not None:
default = kwdefaults.get(name, _empty)
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_KEYWORD_ONLY,
default=default))
# **kwargs
if func_code.co_flags & 0x08:
index = pos_count + keyword_only_count
if func_code.co_flags & 0x04:
index += 1
name = arg_names[index]
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_VAR_KEYWORD))
return cls(parameters,
return_annotation=annotations.get('return', _empty),
__validate_parameters__=False)
@property
def parameters(self):
try:
return types.MappingProxyType(self._parameters)
except AttributeError:
return OrderedDict(self._parameters.items())
@property
def return_annotation(self):
return self._return_annotation
def replace(self, parameters=_void, return_annotation=_void):
'''Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
'''
if parameters is _void:
parameters = self.parameters.values()
if return_annotation is _void:
return_annotation = self._return_annotation
return type(self)(parameters,
return_annotation=return_annotation)
def __hash__(self):
msg = "unhashable type: '{0}'".format(self.__class__.__name__)
raise TypeError(msg)
def __eq__(self, other):
if (not issubclass(type(other), Signature) or
self.return_annotation != other.return_annotation or
len(self.parameters) != len(other.parameters)):
return False
other_positions = dict((param, idx)
for idx, param in enumerate(other.parameters.keys()))
for idx, (param_name, param) in enumerate(self.parameters.items()):
if param.kind == _KEYWORD_ONLY:
try:
other_param = other.parameters[param_name]
except KeyError:
return False
else:
if param != other_param:
return False
else:
try:
other_idx = other_positions[param_name]
except KeyError:
return False
else:
if (idx != other_idx or
param != other.parameters[param_name]):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def _bind(self, args, kwargs, partial=False):
'''Private method. Don't use directly.'''
arguments = OrderedDict()
parameters = iter(self.parameters.values())
parameters_ex = ()
arg_vals = iter(args)
if partial:
# Support for binding arguments to 'functools.partial' objects.
# See 'functools.partial' case in 'signature()' implementation
# for details.
for param_name, param in self.parameters.items():
if (param._partial_kwarg and param_name not in kwargs):
# Simulating 'functools.partial' behavior
kwargs[param_name] = param.default
while True:
# Let's iterate through the positional arguments and corresponding
# parameters
try:
arg_val = next(arg_vals)
except StopIteration:
# No more positional arguments
try:
param = next(parameters)
except StopIteration:
# No more parameters. That's it. Just need to check that
# we have no `kwargs` after this while loop
break
else:
if param.kind == _VAR_POSITIONAL:
# That's OK, just empty *args. Let's start parsing
# kwargs
break
elif param.name in kwargs:
if param.kind == _POSITIONAL_ONLY:
msg = '{arg!r} parameter is positional only, ' \
'but was passed as a keyword'
msg = msg.format(arg=param.name)
raise TypeError(msg)
parameters_ex = (param,)
break
elif (param.kind == _VAR_KEYWORD or
param.default is not _empty):
# That's fine too - we have a default value for this
# parameter. So, lets start parsing `kwargs`, starting
# with the current parameter
parameters_ex = (param,)
break
else:
if partial:
parameters_ex = (param,)
break
else:
msg = '{arg!r} parameter lacking default value'
msg = msg.format(arg=param.name)
raise TypeError(msg)
else:
# We have a positional argument to process
try:
param = next(parameters)
except StopIteration:
raise TypeError('too many positional arguments')
else:
if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
# Looks like we have no parameter for this positional
# argument
raise TypeError('too many positional arguments')
if param.kind == _VAR_POSITIONAL:
# We have an '*args'-like argument, let's fill it with
# all positional arguments we have left and move on to
# the next phase
values = [arg_val]
values.extend(arg_vals)
arguments[param.name] = tuple(values)
break
if param.name in kwargs:
raise TypeError('multiple values for argument '
'{arg!r}'.format(arg=param.name))
arguments[param.name] = arg_val
# Now, we iterate through the remaining parameters to process
# keyword arguments
kwargs_param = None
for param in itertools.chain(parameters_ex, parameters):
if param.kind == _POSITIONAL_ONLY:
# This should never happen in case of a properly built
# Signature object (but let's have this check here
# to ensure correct behaviour just in case)
raise TypeError('{arg!r} parameter is positional only, '
'but was passed as a keyword'. \
format(arg=param.name))
if param.kind == _VAR_KEYWORD:
# Memorize that we have a '**kwargs'-like parameter
kwargs_param = param
continue
param_name = param.name
try:
arg_val = kwargs.pop(param_name)
except KeyError:
# We have no value for this parameter. It's fine though,
# if it has a default value, or it is an '*args'-like
# parameter, left alone by the processing of positional
# arguments.
if (not partial and param.kind != _VAR_POSITIONAL and
param.default is _empty):
raise TypeError('{arg!r} parameter lacking default value'. \
format(arg=param_name))
else:
arguments[param_name] = arg_val
if kwargs:
if kwargs_param is not None:
# Process our '**kwargs'-like parameter
arguments[kwargs_param.name] = kwargs
else:
raise TypeError('too many keyword arguments %r' % kwargs)
return self._bound_arguments_cls(self, arguments)
def bind(*args, **kwargs):
'''Get a BoundArguments object, that maps the passed `args`
and `kwargs` to the function's signature. Raises `TypeError`
if the passed arguments can not be bound.
'''
return args[0]._bind(args[1:], kwargs)
def bind_partial(self, *args, **kwargs):
'''Get a BoundArguments object, that partially maps the
passed `args` and `kwargs` to the function's signature.
Raises `TypeError` if the passed arguments can not be bound.
'''
return self._bind(args, kwargs, partial=True)
def __str__(self):
result = []
render_kw_only_separator = True
for idx, param in enumerate(self.parameters.values()):
formatted = str(param)
kind = param.kind
if kind == _VAR_POSITIONAL:
# OK, we have an '*args'-like parameter, so we won't need
# a '*' to separate keyword-only arguments
render_kw_only_separator = False
elif kind == _KEYWORD_ONLY and render_kw_only_separator:
# We have a keyword-only parameter to render and we haven't
# rendered an '*args'-like parameter before, so add a '*'
# separator to the parameters list ("foo(arg1, *, arg2)" case)
result.append('*')
# This condition should be only triggered once, so
# reset the flag
render_kw_only_separator = False
result.append(formatted)
rendered = '({0})'.format(', '.join(result))
if self.return_annotation is not _empty:
anno = formatannotation(self.return_annotation)
rendered += ' -> {0}'.format(anno)
return rendered
| 30,390 | Python | .py | 678 | 31.415929 | 84 | 0.547816 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,207 | stresstest.py | evilhero_mylar/lib/ConcurrentLogHandler/stresstest.py | #!/usr/bin/env python
""" stresstest.py: A stress-tester for ConcurrentRotatingFileHandler
This utility spawns a bunch of processes that all try to concurrently write to
the same file. This is pretty much the worst-case scenario for my log handler.
Once all of the processes have completed writing to the log file, the output is
compared to see if any log messages have been lost.
In the future, I may also add in support for testing with each process having
multiple threads.
"""
__version__ = '$Id$'
__author__ = 'Lowell Alleman'
import os
import sys
from subprocess import call, Popen, STDOUT
from time import sleep
ROTATE_COUNT = 5000
# local lib; for testing
from cloghandler import ConcurrentRotatingFileHandler
class RotateLogStressTester:
def __init__(self, sharedfile, uniquefile, name="LogStressTester", logger_delay=0):
self.sharedfile = sharedfile
self.uniquefile = uniquefile
self.name = name
self.writeLoops = 100000
self.rotateSize = 128 * 1024
self.rotateCount = ROTATE_COUNT
self.random_sleep_mode = False
self.debug = False
self.logger_delay = logger_delay
def getLogHandler(self, fn):
""" Override this method if you want to test a different logging handler
class. """
return ConcurrentRotatingFileHandler(fn, 'a', self.rotateSize,
self.rotateCount, delay=self.logger_delay,
debug=self.debug)
# To run the test with the standard library's RotatingFileHandler:
# from logging.handlers import RotatingFileHandler
# return RotatingFileHandler(fn, 'a', self.rotateSize, self.rotateCount)
def start(self):
from logging import getLogger, FileHandler, Formatter, DEBUG
self.log = getLogger(self.name)
self.log.setLevel(DEBUG)
formatter = Formatter('%(asctime)s [%(process)d:%(threadName)s] %(levelname)-8s %(name)s: %(message)s')
# Unique log handler (single file)
handler = FileHandler(self.uniquefile, "w")
handler.setLevel(DEBUG)
handler.setFormatter(formatter)
self.log.addHandler(handler)
# If you suspect that the diff stuff isn't working, un comment the next
# line. You should see this show up once per-process.
# self.log.info("Here is a line that should only be in the first output.")
# Setup output used for testing
handler = self.getLogHandler(self.sharedfile)
handler.setLevel(DEBUG)
handler.setFormatter(formatter)
self.log.addHandler(handler)
# If this ever becomes a real "Thread", then remove this line:
self.run()
def run(self):
c = 0
from random import choice, randint
# Use a bunch of random quotes, numbers, and severity levels to mix it up a bit!
msgs = ["I found %d puppies", "There are %d cats in your hatz",
"my favorite number is %d", "I am %d years old.", "1 + 1 = %d",
"%d/0 = DivideByZero", "blah! %d thingies!", "8 15 16 23 48 %d",
"the worlds largest prime number: %d", "%d happy meals!"]
logfuncts = [self.log.debug, self.log.info, self.log.warn, self.log.error]
self.log.info("Starting to write random log message. Loop=%d", self.writeLoops)
while c <= self.writeLoops:
c += 1
msg = choice(msgs)
logfunc = choice(logfuncts)
logfunc(msg, randint(0,99999999))
if self.random_sleep_mode and c % 1000 == 0:
# Sleep from 0-15 seconds
s = randint(1,15)
print("PID %d sleeping for %d seconds" % (os.getpid(), s))
sleep(s)
# break
self.log.info("Done witting random log messages.")
def iter_lognames(logfile, count):
""" Generator for log file names based on a rotation scheme """
for i in range(count -1, 0, -1):
yield "%s.%d" % (logfile, i)
yield logfile
def iter_logs(iterable, missing_ok=False):
""" Generator to extract log entries from shared log file. """
for fn in iterable:
if os.path.exists(fn):
for line in open(fn):
yield line
elif not missing_ok:
raise ValueError("Missing log file %s" % fn)
def combine_logs(combinedlog, iterable, mode="w"):
""" write all lines (iterable) into a single log file. """
fp = open(combinedlog, mode)
for chunk in iterable:
fp.write(chunk)
fp.close()
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog",
version=__version__,
description="Stress test the cloghandler module.")
parser.add_option("--log-calls", metavar="NUM",
action="store", type="int", default=50000,
help="Number of logging entries to write to each log file. "
"Default is %default")
parser.add_option("--random-sleep-mode",
action="store_true", default=False)
parser.add_option("--debug",
action="store_true", default=False)
parser.add_option("--logger-delay",
action="store_true", default=False,
help="Enable the 'delay' mode in the logger class. "
"This means that the log file will be opened on demand.")
def main_client(args):
(options, args) = parser.parse_args(args)
if len(args) != 2:
raise ValueError("Require 2 arguments. We have %d args" % len(args))
(shared, client) = args
if os.path.isfile(client):
sys.stderr.write("Already a client using output file %s\n" % client)
sys.exit(1)
tester = RotateLogStressTester(shared, client, logger_delay=options.logger_delay)
tester.random_sleep_mode = options.random_sleep_mode
tester.debug = options.debug
tester.writeLoops = options.log_calls
tester.start()
print("We are done pid=%d" % os.getpid())
class TestManager:
class ChildProc(object):
""" Very simple child container class."""
__slots__ = [ "popen", "sharedfile", "clientfile" ]
def __init__(self, **kwargs):
self.update(**kwargs)
def update(self, **kwargs):
for key, val in kwargs.items():
setattr(self, key, val)
def __init__(self):
self.tests = []
def launchPopen(self, *args, **kwargs):
proc = Popen(*args, **kwargs)
cp = self.ChildProc(popen=proc)
self.tests.append(cp)
return cp
def wait(self, check_interval=3):
""" Wait for all child test processes to complete. """
print("Waiting while children are out running and playing!")
while True:
sleep(check_interval)
waiting = []
for cp in self.tests:
if cp.popen.poll() is None:
waiting.append(cp.popen.pid)
if not waiting:
break
print("Waiting on %r " % waiting)
print("All children have stopped.")
def checkExitCodes(self):
for cp in self.tests:
if cp.popen.poll() != 0:
return False
return True
def unified_diff(a,b, out=sys.stdout):
import difflib
ai = open(a).readlines()
bi = open(b).readlines()
for line in difflib.unified_diff(ai, bi, a, b):
out.write(line)
def main_runner(args):
parser.add_option("--processes", metavar="NUM",
action="store", type="int", default=3,
help="Number of processes to spawn. Default: %default")
parser.add_option("--delay", metavar="secs",
action="store", type="float", default=2.5,
help="Wait SECS before spawning next processes. "
"Default: %default")
parser.add_option("-p", "--path", metavar="DIR",
action="store", default="test",
help="Path to a temporary directory. Default: '%default'")
this_script = args[0]
(options, args) = parser.parse_args(args)
options.path = os.path.abspath(options.path)
if not os.path.isdir(options.path):
os.makedirs(options.path)
manager = TestManager()
shared = os.path.join(options.path, "shared.log")
for client_id in range(options.processes):
client = os.path.join(options.path, "client.log_client%s.log" % client_id)
cmdline = [ sys.executable, this_script, "client", shared, client,
"--log-calls=%d" % options.log_calls ]
if options.random_sleep_mode:
cmdline.append("--random-sleep-mode")
if options.debug:
cmdline.append("--debug")
if options.logger_delay:
cmdline.append("--logger-delay")
child = manager.launchPopen(cmdline)
child.update(sharedfile=shared, clientfile=client)
sleep(options.delay)
# Wait for all of the subprocesses to exit
manager.wait()
# Check children exit codes
if not manager.checkExitCodes():
sys.stderr.write("One or more of the child process has failed.\n"
"Aborting test.\n")
sys.exit(2)
client_combo = os.path.join(options.path, "client.log.combo")
shared_combo = os.path.join(options.path, "shared.log.combo")
# Combine all of the log files...
client_files = [ child.clientfile for child in manager.tests ]
if False:
def sort_em(iterable):
return iterable
else:
sort_em = sorted
print("Writing out combined client logs...")
combine_logs(client_combo, sort_em(iter_logs(client_files)))
print("done.")
print("Writing out combined shared logs...")
shared_log_files = iter_lognames(shared, ROTATE_COUNT)
log_lines = iter_logs(shared_log_files, missing_ok=True)
combine_logs(shared_combo, sort_em(log_lines))
print("done.")
print("Running internal diff: (If the next line is 'end of diff', then the stress test passed!)")
unified_diff(client_combo, shared_combo)
print(" --- end of diff ----")
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1].lower() == "client":
main_client(sys.argv[2:])
else:
main_runner(sys.argv)
| 10,516 | Python | .py | 232 | 35.603448 | 112 | 0.616863 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,208 | cloghandler.py | evilhero_mylar/lib/ConcurrentLogHandler/cloghandler.py | # Copyright 2013 Lowell Alleman
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
""" cloghandler.py: A smart replacement for the standard RotatingFileHandler
ConcurrentRotatingFileHandler: This class is a log handler which is a drop-in
replacement for the python standard log handler 'RotateFileHandler', the primary
difference being that this handler will continue to write to the same file if
the file cannot be rotated for some reason, whereas the RotatingFileHandler will
strictly adhere to the maximum file size. Unfortunately, if you are using the
RotatingFileHandler on Windows, you will find that once an attempted rotation
fails, all subsequent log messages are dropped. The other major advantage of
this module is that multiple processes can safely write to a single log file.
To put it another way: This module's top priority is preserving your log
records, whereas the standard library attempts to limit disk usage, which can
potentially drop log messages. If you are trying to determine which module to
use, there are number of considerations: What is most important: strict disk
space usage or preservation of log messages? What OSes are you supporting? Can
you afford to have processes blocked by file locks?
Concurrent access is handled by using file locks, which should ensure that log
messages are not dropped or clobbered. This means that a file lock is acquired
and released for every log message that is written to disk. (On Windows, you may
also run into a temporary situation where the log file must be opened and closed
for each log message.) This can have potentially performance implications. In my
testing, performance was more than adequate, but if you need a high-volume or
low-latency solution, I suggest you look elsewhere.
This module currently only support the 'nt' and 'posix' platforms due to the
usage of the portalocker module. I do not have access to any other platforms
for testing, patches are welcome.
See the README file for an example usage of this module.
This module supports Python 2.6 and later.
"""
__version__ = '0.9.1'
__revision__ = 'lowell87@gmail.com-20130711022321-doutxl7zyzuwss5a 2013-07-10 22:23:21 -0400 [0]'
__author__ = "Lowell Alleman"
__all__ = [
"ConcurrentRotatingHandler",
]
import os
import sys
from random import randint
from logging import Handler, LogRecord
from logging.handlers import BaseRotatingHandler
try:
import codecs
except ImportError:
codecs = None
# Question/TODO: Should we have a fallback mode if we can't load portalocker /
# we should still be better off than with the standard RotattingFileHandler
# class, right? We do some rename checking... that should prevent some file
# clobbering that the builtin class allows.
# sibling module than handles all the ugly platform-specific details of file locking
from portalocker import lock, unlock, LOCK_EX, LOCK_NB, LockException
# Workaround for handleError() in Python 2.7+ where record is written to stderr
class NullLogRecord(LogRecord):
def __init__(self):
pass
def __getattr__(self, attr):
return None
class ConcurrentRotatingFileHandler(BaseRotatingHandler):
"""
Handler for logging to a set of files, which switches from one file to the
next when the current file reaches a certain size. Multiple processes can
write to the log file concurrently, but this may mean that the file will
exceed the given size.
"""
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0,
encoding=None, debug=True, delay=0):
"""
Open the specified file and use it as the stream for logging.
By default, the file grows indefinitely. You can specify particular
values of maxBytes and backupCount to allow the file to rollover at
a predetermined size.
Rollover occurs whenever the current log file is nearly maxBytes in
length. If backupCount is >= 1, the system will successively create
new files with the same pathname as the base file, but with extensions
".1", ".2" etc. appended to it. For example, with a backupCount of 5
and a base file name of "app.log", you would get "app.log",
"app.log.1", "app.log.2", ... through to "app.log.5". The file being
written to is always "app.log" - when it gets filled up, it is closed
and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
exist, then they are renamed to "app.log.2", "app.log.3" etc.
respectively.
If maxBytes is zero, rollover never occurs.
On Windows, it is not possible to rename a file that is currently opened
by another process. This means that it is not possible to rotate the
log files if multiple processes is using the same log file. In this
case, the current log file will continue to grow until the rotation can
be completed successfully. In order for rotation to be possible, all of
the other processes need to close the file first. A mechanism, called
"degraded" mode, has been created for this scenario. In degraded mode,
the log file is closed after each log message is written. So once all
processes have entered degraded mode, the net rotation attempt should
be successful and then normal logging can be resumed. Using the 'delay'
parameter may help reduce contention in some usage patterns.
This log handler assumes that all concurrent processes logging to a
single file will are using only this class, and that the exact same
parameters are provided to each instance of this class. If, for
example, two different processes are using this class, but with
different values for 'maxBytes' or 'backupCount', then odd behavior is
expected. The same is true if this class is used by one application, but
the RotatingFileHandler is used by another.
"""
# Absolute file name handling done by FileHandler since Python 2.5
BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
self.delay = delay
self._rotateFailed = False
self.maxBytes = maxBytes
self.backupCount = backupCount
self._open_lockfile()
# For debug mode, swap out the "_degrade()" method with a more a verbose one.
if debug:
self._degrade = self._degrade_debug
def _open_lockfile(self):
# Use 'file.lock' and not 'file.log.lock' (Only handles the normal "*.log" case.)
if self.baseFilename.endswith(".log"):
lock_file = self.baseFilename[:-4]
else:
lock_file = self.baseFilename
lock_file += ".lock"
self.stream_lock = open(lock_file,"w")
def _open(self, mode=None):
"""
Open the current base file with the (original) mode and encoding.
Return the resulting stream.
Note: Copied from stdlib. Added option to override 'mode'
"""
if mode is None:
mode = self.mode
if self.encoding is None:
stream = open(self.baseFilename, mode)
else:
stream = codecs.open(self.baseFilename, mode, self.encoding)
return stream
def _close(self):
""" Close file stream. Unlike close(), we don't tear anything down, we
expect the log to be re-opened after rotation."""
if self.stream:
try:
if not self.stream.closed:
# Flushing probably isn't technically necessary, but it feels right
self.stream.flush()
self.stream.close()
finally:
self.stream = None
def acquire(self):
""" Acquire thread and file locks. Re-opening log for 'degraded' mode.
"""
# handle thread lock
Handler.acquire(self)
# Issue a file lock. (This is inefficient for multiple active threads
# within a single process. But if you're worried about high-performance,
# you probably aren't using this log handler.)
if self.stream_lock:
# If stream_lock=None, then assume close() was called or something
# else weird and ignore all file-level locks.
if self.stream_lock.closed:
# Daemonization can close all open file descriptors, see
# https://bugzilla.redhat.com/show_bug.cgi?id=952929
# Try opening the lock file again. Should we warn() here?!?
try:
self._open_lockfile()
except Exception:
self.handleError(NullLogRecord())
# Don't try to open the stream lock again
self.stream_lock = None
return
lock(self.stream_lock, LOCK_EX)
# Stream will be opened as part by FileHandler.emit()
def release(self):
""" Release file and thread locks. If in 'degraded' mode, close the
stream to reduce contention until the log files can be rotated. """
try:
if self._rotateFailed:
self._close()
except Exception:
self.handleError(NullLogRecord())
finally:
try:
if self.stream_lock and not self.stream_lock.closed:
unlock(self.stream_lock)
except Exception:
self.handleError(NullLogRecord())
finally:
# release thread lock
Handler.release(self)
def close(self):
"""
Close log stream and stream_lock. """
try:
self._close()
if not self.stream_lock.closed:
self.stream_lock.close()
finally:
self.stream_lock = None
Handler.close(self)
def _degrade(self, degrade, msg, *args):
""" Set degrade mode or not. Ignore msg. """
self._rotateFailed = degrade
del msg, args # avoid pychecker warnings
def _degrade_debug(self, degrade, msg, *args):
""" A more colorful version of _degade(). (This is enabled by passing
"debug=True" at initialization).
"""
if degrade:
if not self._rotateFailed:
sys.stderr.write("Degrade mode - ENTERING - (pid=%d) %s\n" %
(os.getpid(), msg % args))
self._rotateFailed = True
else:
if self._rotateFailed:
sys.stderr.write("Degrade mode - EXITING - (pid=%d) %s\n" %
(os.getpid(), msg % args))
self._rotateFailed = False
def doRollover(self):
"""
Do a rollover, as described in __init__().
"""
self._close()
if self.backupCount <= 0:
# Don't keep any backups, just overwrite the existing backup file
# Locking doesn't much matter here; since we are overwriting it anyway
self.stream = self._open("w")
return
try:
# Determine if we can rename the log file or not. Windows refuses to
# rename an open file, Unix is inode base so it doesn't care.
# Attempt to rename logfile to tempname: There is a slight race-condition here, but it seems unavoidable
tmpname = None
while not tmpname or os.path.exists(tmpname):
tmpname = "%s.rotate.%08d" % (self.baseFilename, randint(0,99999999))
try:
# Do a rename test to determine if we can successfully rename the log file
os.rename(self.baseFilename, tmpname)
except (IOError, OSError):
exc_value = sys.exc_info()[1]
self._degrade(True, "rename failed. File in use? "
"exception=%s", exc_value)
return
# Q: Is there some way to protect this code from a KeboardInterupt?
# This isn't necessarily a data loss issue, but it certainly does
# break the rotation process during stress testing.
# There is currently no mechanism in place to handle the situation
# where one of these log files cannot be renamed. (Example, user
# opens "logfile.3" in notepad); we could test rename each file, but
# nobody's complained about this being an issue; so the additional
# code complexity isn't warranted.
for i in range(self.backupCount - 1, 0, -1):
sfn = "%s.%d" % (self.baseFilename, i)
dfn = "%s.%d" % (self.baseFilename, i + 1)
if os.path.exists(sfn):
#print "%s -> %s" % (sfn, dfn)
if os.path.exists(dfn):
os.remove(dfn)
os.rename(sfn, dfn)
dfn = self.baseFilename + ".1"
if os.path.exists(dfn):
os.remove(dfn)
os.rename(tmpname, dfn)
#print "%s -> %s" % (self.baseFilename, dfn)
self._degrade(False, "Rotation completed")
finally:
# Re-open the output stream, but if "delay" is enabled then wait
# until the next emit() call. This could reduce rename contention in
# some usage patterns.
if not self.delay:
self.stream = self._open()
def shouldRollover(self, record):
"""
Determine if rollover should occur.
For those that are keeping track. This differs from the standard
library's RotatingLogHandler class. Because there is no promise to keep
the file size under maxBytes we ignore the length of the current record.
"""
del record # avoid pychecker warnings
# Is stream is not yet open, skip rollover check. (Check will occur on
# next message, after emit() calls _open())
if self.stream is None:
return False
if self._shouldRollover():
# If some other process already did the rollover (which is possible
# on Unix) the file our stream may now be named "log.1", thus
# triggering another rollover. Avoid this by closing and opening
# "log" again.
self._close()
self.stream = self._open()
return self._shouldRollover()
return False
def _shouldRollover(self):
if self.maxBytes > 0: # are we rolling over?
self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
if self.stream.tell() >= self.maxBytes:
return True
else:
self._degrade(False, "Rotation done or not needed at this time")
return False
# Publish this class to the "logging.handlers" module so that it can be use
# from a logging config file via logging.config.fileConfig().
import logging.handlers
logging.handlers.ConcurrentRotatingFileHandler = ConcurrentRotatingFileHandler
| 15,685 | Python | .py | 307 | 41.247557 | 117 | 0.64562 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,209 | portalocker.py | evilhero_mylar/lib/ConcurrentLogHandler/portalocker.py | # portalocker.py - Cross-platform (posix/nt) API for flock-style file locking.
# Requires python 1.5.2 or better.
"""Cross-platform (posix/nt) API for flock-style file locking.
Synopsis:
import portalocker
file = open("somefile", "r+")
portalocker.lock(file, portalocker.LOCK_EX)
file.seek(12)
file.write("foo")
file.close()
If you know what you're doing, you may choose to
portalocker.unlock(file)
before closing the file, but why?
Methods:
lock( file, flags )
unlock( file )
Constants:
LOCK_EX
LOCK_SH
LOCK_NB
Exceptions:
LockException
Notes:
For the 'nt' platform, this module requires the Python Extensions for Windows.
Be aware that this may not work as expected on Windows 95/98/ME.
History:
I learned the win32 technique for locking files from sample code
provided by John Nielsen <nielsenjf@my-deja.com> in the documentation
that accompanies the win32 modules.
Author: Jonathan Feinberg <jdf@pobox.com>,
Lowell Alleman <lalleman@mfps.com>,
Rick van Hattem <Rick.van.Hattem@Fawo.nl>
Version: 0.3
URL: https://github.com/WoLpH/portalocker
"""
__all__ = [
"lock",
"unlock",
"LOCK_EX",
"LOCK_SH",
"LOCK_NB",
"LockException",
]
import os
class LockException(Exception):
# Error codes:
LOCK_FAILED = 1
if os.name == 'nt':
import win32con
import win32file
import pywintypes
LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
LOCK_SH = 0 # the default
LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
# is there any reason not to reuse the following structure?
__overlapped = pywintypes.OVERLAPPED()
elif os.name == 'posix':
import fcntl
LOCK_EX = fcntl.LOCK_EX
LOCK_SH = fcntl.LOCK_SH
LOCK_NB = fcntl.LOCK_NB
else:
raise RuntimeError("PortaLocker only defined for nt and posix platforms")
if os.name == 'nt':
def lock(file, flags):
hfile = win32file._get_osfhandle(file.fileno())
try:
win32file.LockFileEx(hfile, flags, 0, -0x10000, __overlapped)
except pywintypes.error, exc_value:
# error: (33, 'LockFileEx', 'The process cannot access the file because another process has locked a portion of the file.')
if exc_value[0] == 33:
raise LockException(LockException.LOCK_FAILED, exc_value[2])
else:
# Q: Are there exceptions/codes we should be dealing with here?
raise
def unlock(file):
hfile = win32file._get_osfhandle(file.fileno())
try:
win32file.UnlockFileEx(hfile, 0, -0x10000, __overlapped)
except pywintypes.error, exc_value:
if exc_value[0] == 158:
# error: (158, 'UnlockFileEx', 'The segment is already unlocked.')
# To match the 'posix' implementation, silently ignore this error
pass
else:
# Q: Are there exceptions/codes we should be dealing with here?
raise
elif os.name == 'posix':
def lock(file, flags):
try:
fcntl.flock(file.fileno(), flags)
except IOError, exc_value:
# The exception code varies on different systems so we'll catch
# every IO error
raise LockException(*exc_value)
def unlock(file):
fcntl.flock(file.fileno(), fcntl.LOCK_UN)
if __name__ == '__main__':
from time import time, strftime, localtime
import sys
import portalocker
log = open('log.txt', "a+")
portalocker.lock(log, portalocker.LOCK_EX)
timestamp = strftime("%m/%d/%Y %H:%M:%S\n", localtime(time()))
log.write( timestamp )
print "Wrote lines. Hit enter to release lock."
dummy = sys.stdin.readline()
log.close()
| 3,780 | Python | .py | 108 | 28.731481 | 135 | 0.654365 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,210 | _compat.py | evilhero_mylar/lib/markupsafe/_compat.py | # -*- coding: utf-8 -*-
"""
markupsafe._compat
~~~~~~~~~~~~~~~~~~
Compatibility module for different Python versions.
:copyright: (c) 2013 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
text_type = str
string_types = (str,)
unichr = chr
int_types = (int,)
iteritems = lambda x: iter(x.items())
else:
text_type = unicode
string_types = (str, unicode)
unichr = unichr
int_types = (int, long)
iteritems = lambda x: x.iteritems()
| 565 | Python | .py | 22 | 21.772727 | 55 | 0.619666 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,211 | __init__.py | evilhero_mylar/lib/markupsafe/__init__.py | # -*- coding: utf-8 -*-
"""
markupsafe
~~~~~~~~~~
Implements a Markup string.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import re
import string
from collections import Mapping
from markupsafe._compat import text_type, string_types, int_types, \
unichr, iteritems, PY2
__all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']
_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')
_entity_re = re.compile(r'&([^;]+);')
class Markup(text_type):
r"""Marks a string as being safe for inclusion in HTML/XML output without
needing to be escaped. This implements the `__html__` interface a couple
of frameworks and web applications use. :class:`Markup` is a direct
subclass of `unicode` and provides all the methods of `unicode` just that
it escapes arguments passed and always returns `Markup`.
The `escape` function returns markup objects so that double escaping can't
happen.
The constructor of the :class:`Markup` class can be used for three
different things: When passed an unicode object it's assumed to be safe,
when passed an object with an HTML representation (has an `__html__`
method) that representation is used, otherwise the object passed is
converted into a unicode string and then assumed to be safe:
>>> Markup("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
>>> class Foo(object):
... def __html__(self):
... return '<a href="#">foo</a>'
...
>>> Markup(Foo())
Markup(u'<a href="#">foo</a>')
If you want object passed being always treated as unsafe you can use the
:meth:`escape` classmethod to create a :class:`Markup` object:
>>> Markup.escape("Hello <em>World</em>!")
Markup(u'Hello <em>World</em>!')
Operations on a markup string are markup aware which means that all
arguments are passed through the :func:`escape` function:
>>> em = Markup("<em>%s</em>")
>>> em % "foo & bar"
Markup(u'<em>foo & bar</em>')
>>> strong = Markup("<strong>%(text)s</strong>")
>>> strong % {'text': '<blink>hacker here</blink>'}
Markup(u'<strong><blink>hacker here</blink></strong>')
>>> Markup("<em>Hello</em> ") + "<foo>"
Markup(u'<em>Hello</em> <foo>')
"""
__slots__ = ()
def __new__(cls, base=u'', encoding=None, errors='strict'):
if hasattr(base, '__html__'):
base = base.__html__()
if encoding is None:
return text_type.__new__(cls, base)
return text_type.__new__(cls, base, encoding, errors)
def __html__(self):
return self
def __add__(self, other):
if isinstance(other, string_types) or hasattr(other, '__html__'):
return self.__class__(super(Markup, self).__add__(self.escape(other)))
return NotImplemented
def __radd__(self, other):
if hasattr(other, '__html__') or isinstance(other, string_types):
return self.escape(other).__add__(self)
return NotImplemented
def __mul__(self, num):
if isinstance(num, int_types):
return self.__class__(text_type.__mul__(self, num))
return NotImplemented
__rmul__ = __mul__
def __mod__(self, arg):
if isinstance(arg, tuple):
arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)
else:
arg = _MarkupEscapeHelper(arg, self.escape)
return self.__class__(text_type.__mod__(self, arg))
def __repr__(self):
return '%s(%s)' % (
self.__class__.__name__,
text_type.__repr__(self)
)
def join(self, seq):
return self.__class__(text_type.join(self, map(self.escape, seq)))
join.__doc__ = text_type.join.__doc__
def split(self, *args, **kwargs):
return list(map(self.__class__, text_type.split(self, *args, **kwargs)))
split.__doc__ = text_type.split.__doc__
def rsplit(self, *args, **kwargs):
return list(map(self.__class__, text_type.rsplit(self, *args, **kwargs)))
rsplit.__doc__ = text_type.rsplit.__doc__
def splitlines(self, *args, **kwargs):
return list(map(self.__class__, text_type.splitlines(
self, *args, **kwargs)))
splitlines.__doc__ = text_type.splitlines.__doc__
def unescape(self):
r"""Unescape markup again into an text_type string. This also resolves
known HTML4 and XHTML entities:
>>> Markup("Main » <em>About</em>").unescape()
u'Main \xbb <em>About</em>'
"""
from markupsafe._constants import HTML_ENTITIES
def handle_match(m):
name = m.group(1)
if name in HTML_ENTITIES:
return unichr(HTML_ENTITIES[name])
try:
if name[:2] in ('#x', '#X'):
return unichr(int(name[2:], 16))
elif name.startswith('#'):
return unichr(int(name[1:]))
except ValueError:
pass
return u''
return _entity_re.sub(handle_match, text_type(self))
def striptags(self):
r"""Unescape markup into an text_type string and strip all tags. This
also resolves known HTML4 and XHTML entities. Whitespace is
normalized to one:
>>> Markup("Main » <em>About</em>").striptags()
u'Main \xbb About'
"""
stripped = u' '.join(_striptags_re.sub('', self).split())
return Markup(stripped).unescape()
@classmethod
def escape(cls, s):
"""Escape the string. Works like :func:`escape` with the difference
that for subclasses of :class:`Markup` this function would return the
correct subclass.
"""
rv = escape(s)
if rv.__class__ is not cls:
return cls(rv)
return rv
def make_simple_escaping_wrapper(name):
orig = getattr(text_type, name)
def func(self, *args, **kwargs):
args = _escape_argspec(list(args), enumerate(args), self.escape)
_escape_argspec(kwargs, iteritems(kwargs), self.escape)
return self.__class__(orig(self, *args, **kwargs))
func.__name__ = orig.__name__
func.__doc__ = orig.__doc__
return func
for method in '__getitem__', 'capitalize', \
'title', 'lower', 'upper', 'replace', 'ljust', \
'rjust', 'lstrip', 'rstrip', 'center', 'strip', \
'translate', 'expandtabs', 'swapcase', 'zfill':
locals()[method] = make_simple_escaping_wrapper(method)
# new in python 2.5
if hasattr(text_type, 'partition'):
def partition(self, sep):
return tuple(map(self.__class__,
text_type.partition(self, self.escape(sep))))
def rpartition(self, sep):
return tuple(map(self.__class__,
text_type.rpartition(self, self.escape(sep))))
# new in python 2.6
if hasattr(text_type, 'format'):
def format(*args, **kwargs):
self, args = args[0], args[1:]
formatter = EscapeFormatter(self.escape)
kwargs = _MagicFormatMapping(args, kwargs)
return self.__class__(formatter.vformat(self, args, kwargs))
def __html_format__(self, format_spec):
if format_spec:
raise ValueError('Unsupported format specification '
'for Markup.')
return self
# not in python 3
if hasattr(text_type, '__getslice__'):
__getslice__ = make_simple_escaping_wrapper('__getslice__')
del method, make_simple_escaping_wrapper
class _MagicFormatMapping(Mapping):
"""This class implements a dummy wrapper to fix a bug in the Python
standard library for string formatting.
See http://bugs.python.org/issue13598 for information about why
this is necessary.
"""
def __init__(self, args, kwargs):
self._args = args
self._kwargs = kwargs
self._last_index = 0
def __getitem__(self, key):
if key == '':
idx = self._last_index
self._last_index += 1
try:
return self._args[idx]
except LookupError:
pass
key = str(idx)
return self._kwargs[key]
def __iter__(self):
return iter(self._kwargs)
def __len__(self):
return len(self._kwargs)
if hasattr(text_type, 'format'):
class EscapeFormatter(string.Formatter):
def __init__(self, escape):
self.escape = escape
def format_field(self, value, format_spec):
if hasattr(value, '__html_format__'):
rv = value.__html_format__(format_spec)
elif hasattr(value, '__html__'):
if format_spec:
raise ValueError('No format specification allowed '
'when formatting an object with '
'its __html__ method.')
rv = value.__html__()
else:
rv = string.Formatter.format_field(self, value, format_spec)
return text_type(self.escape(rv))
def _escape_argspec(obj, iterable, escape):
"""Helper for various string-wrapped functions."""
for key, value in iterable:
if hasattr(value, '__html__') or isinstance(value, string_types):
obj[key] = escape(value)
return obj
class _MarkupEscapeHelper(object):
"""Helper for Markup.__mod__"""
def __init__(self, obj, escape):
self.obj = obj
self.escape = escape
__getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x], s.escape)
__unicode__ = __str__ = lambda s: text_type(s.escape(s.obj))
__repr__ = lambda s: str(s.escape(repr(s.obj)))
__int__ = lambda s: int(s.obj)
__float__ = lambda s: float(s.obj)
# we have to import it down here as the speedups and native
# modules imports the markup type which is define above.
try:
from markupsafe._speedups import escape, escape_silent, soft_unicode
except ImportError:
from markupsafe._native import escape, escape_silent, soft_unicode
if not PY2:
soft_str = soft_unicode
__all__.append('soft_str')
| 10,338 | Python | .py | 240 | 34.283333 | 82 | 0.585857 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,212 | _constants.py | evilhero_mylar/lib/markupsafe/_constants.py | # -*- coding: utf-8 -*-
"""
markupsafe._constants
~~~~~~~~~~~~~~~~~~~~~
Highlevel implementation of the Markup string.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
HTML_ENTITIES = {
'AElig': 198,
'Aacute': 193,
'Acirc': 194,
'Agrave': 192,
'Alpha': 913,
'Aring': 197,
'Atilde': 195,
'Auml': 196,
'Beta': 914,
'Ccedil': 199,
'Chi': 935,
'Dagger': 8225,
'Delta': 916,
'ETH': 208,
'Eacute': 201,
'Ecirc': 202,
'Egrave': 200,
'Epsilon': 917,
'Eta': 919,
'Euml': 203,
'Gamma': 915,
'Iacute': 205,
'Icirc': 206,
'Igrave': 204,
'Iota': 921,
'Iuml': 207,
'Kappa': 922,
'Lambda': 923,
'Mu': 924,
'Ntilde': 209,
'Nu': 925,
'OElig': 338,
'Oacute': 211,
'Ocirc': 212,
'Ograve': 210,
'Omega': 937,
'Omicron': 927,
'Oslash': 216,
'Otilde': 213,
'Ouml': 214,
'Phi': 934,
'Pi': 928,
'Prime': 8243,
'Psi': 936,
'Rho': 929,
'Scaron': 352,
'Sigma': 931,
'THORN': 222,
'Tau': 932,
'Theta': 920,
'Uacute': 218,
'Ucirc': 219,
'Ugrave': 217,
'Upsilon': 933,
'Uuml': 220,
'Xi': 926,
'Yacute': 221,
'Yuml': 376,
'Zeta': 918,
'aacute': 225,
'acirc': 226,
'acute': 180,
'aelig': 230,
'agrave': 224,
'alefsym': 8501,
'alpha': 945,
'amp': 38,
'and': 8743,
'ang': 8736,
'apos': 39,
'aring': 229,
'asymp': 8776,
'atilde': 227,
'auml': 228,
'bdquo': 8222,
'beta': 946,
'brvbar': 166,
'bull': 8226,
'cap': 8745,
'ccedil': 231,
'cedil': 184,
'cent': 162,
'chi': 967,
'circ': 710,
'clubs': 9827,
'cong': 8773,
'copy': 169,
'crarr': 8629,
'cup': 8746,
'curren': 164,
'dArr': 8659,
'dagger': 8224,
'darr': 8595,
'deg': 176,
'delta': 948,
'diams': 9830,
'divide': 247,
'eacute': 233,
'ecirc': 234,
'egrave': 232,
'empty': 8709,
'emsp': 8195,
'ensp': 8194,
'epsilon': 949,
'equiv': 8801,
'eta': 951,
'eth': 240,
'euml': 235,
'euro': 8364,
'exist': 8707,
'fnof': 402,
'forall': 8704,
'frac12': 189,
'frac14': 188,
'frac34': 190,
'frasl': 8260,
'gamma': 947,
'ge': 8805,
'gt': 62,
'hArr': 8660,
'harr': 8596,
'hearts': 9829,
'hellip': 8230,
'iacute': 237,
'icirc': 238,
'iexcl': 161,
'igrave': 236,
'image': 8465,
'infin': 8734,
'int': 8747,
'iota': 953,
'iquest': 191,
'isin': 8712,
'iuml': 239,
'kappa': 954,
'lArr': 8656,
'lambda': 955,
'lang': 9001,
'laquo': 171,
'larr': 8592,
'lceil': 8968,
'ldquo': 8220,
'le': 8804,
'lfloor': 8970,
'lowast': 8727,
'loz': 9674,
'lrm': 8206,
'lsaquo': 8249,
'lsquo': 8216,
'lt': 60,
'macr': 175,
'mdash': 8212,
'micro': 181,
'middot': 183,
'minus': 8722,
'mu': 956,
'nabla': 8711,
'nbsp': 160,
'ndash': 8211,
'ne': 8800,
'ni': 8715,
'not': 172,
'notin': 8713,
'nsub': 8836,
'ntilde': 241,
'nu': 957,
'oacute': 243,
'ocirc': 244,
'oelig': 339,
'ograve': 242,
'oline': 8254,
'omega': 969,
'omicron': 959,
'oplus': 8853,
'or': 8744,
'ordf': 170,
'ordm': 186,
'oslash': 248,
'otilde': 245,
'otimes': 8855,
'ouml': 246,
'para': 182,
'part': 8706,
'permil': 8240,
'perp': 8869,
'phi': 966,
'pi': 960,
'piv': 982,
'plusmn': 177,
'pound': 163,
'prime': 8242,
'prod': 8719,
'prop': 8733,
'psi': 968,
'quot': 34,
'rArr': 8658,
'radic': 8730,
'rang': 9002,
'raquo': 187,
'rarr': 8594,
'rceil': 8969,
'rdquo': 8221,
'real': 8476,
'reg': 174,
'rfloor': 8971,
'rho': 961,
'rlm': 8207,
'rsaquo': 8250,
'rsquo': 8217,
'sbquo': 8218,
'scaron': 353,
'sdot': 8901,
'sect': 167,
'shy': 173,
'sigma': 963,
'sigmaf': 962,
'sim': 8764,
'spades': 9824,
'sub': 8834,
'sube': 8838,
'sum': 8721,
'sup': 8835,
'sup1': 185,
'sup2': 178,
'sup3': 179,
'supe': 8839,
'szlig': 223,
'tau': 964,
'there4': 8756,
'theta': 952,
'thetasym': 977,
'thinsp': 8201,
'thorn': 254,
'tilde': 732,
'times': 215,
'trade': 8482,
'uArr': 8657,
'uacute': 250,
'uarr': 8593,
'ucirc': 251,
'ugrave': 249,
'uml': 168,
'upsih': 978,
'upsilon': 965,
'uuml': 252,
'weierp': 8472,
'xi': 958,
'yacute': 253,
'yen': 165,
'yuml': 255,
'zeta': 950,
'zwj': 8205,
'zwnj': 8204
}
| 4,795 | Python | .py | 263 | 13.292776 | 50 | 0.47659 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,213 | tests.py | evilhero_mylar/lib/markupsafe/tests.py | # -*- coding: utf-8 -*-
import gc
import sys
import unittest
from markupsafe import Markup, escape, escape_silent
from markupsafe._compat import text_type
class MarkupTestCase(unittest.TestCase):
def test_adding(self):
# adding two strings should escape the unsafe one
unsafe = '<script type="application/x-some-script">alert("foo");</script>'
safe = Markup('<em>username</em>')
assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)
def test_string_interpolation(self):
# string interpolations are safe to use too
assert Markup('<em>%s</em>') % '<bad user>' == \
'<em><bad user></em>'
assert Markup('<em>%(username)s</em>') % {
'username': '<bad user>'
} == '<em><bad user></em>'
assert Markup('%i') % 3.14 == '3'
assert Markup('%.2f') % 3.14 == '3.14'
def test_type_behavior(self):
# an escaped object is markup too
assert type(Markup('foo') + 'bar') is Markup
# and it implements __html__ by returning itself
x = Markup("foo")
assert x.__html__() is x
def test_html_interop(self):
# it also knows how to treat __html__ objects
class Foo(object):
def __html__(self):
return '<em>awesome</em>'
def __unicode__(self):
return 'awesome'
__str__ = __unicode__
assert Markup(Foo()) == '<em>awesome</em>'
assert Markup('<strong>%s</strong>') % Foo() == \
'<strong><em>awesome</em></strong>'
def test_tuple_interpol(self):
self.assertEqual(Markup('<em>%s:%s</em>') % (
'<foo>',
'<bar>',
), Markup(u'<em><foo>:<bar></em>'))
def test_dict_interpol(self):
self.assertEqual(Markup('<em>%(foo)s</em>') % {
'foo': '<foo>',
}, Markup(u'<em><foo></em>'))
self.assertEqual(Markup('<em>%(foo)s:%(bar)s</em>') % {
'foo': '<foo>',
'bar': '<bar>',
}, Markup(u'<em><foo>:<bar></em>'))
def test_escaping(self):
# escaping and unescaping
assert escape('"<>&\'') == '"<>&''
assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar"
assert Markup("<test>").unescape() == "<test>"
def test_formatting(self):
for actual, expected in (
(Markup('%i') % 3.14, '3'),
(Markup('%.2f') % 3.14159, '3.14'),
(Markup('%s %s %s') % ('<', 123, '>'), '< 123 >'),
(Markup('<em>{awesome}</em>').format(awesome='<awesome>'),
'<em><awesome></em>'),
(Markup('{0[1][bar]}').format([0, {'bar': '<bar/>'}]),
'<bar/>'),
(Markup('{0[1][bar]}').format([0, {'bar': Markup('<bar/>')}]),
'<bar/>')):
assert actual == expected, "%r should be %r!" % (actual, expected)
# This is new in 2.7
if sys.version_info >= (2, 7):
def test_formatting_empty(self):
formatted = Markup('{}').format(0)
assert formatted == Markup('0')
def test_custom_formatting(self):
class HasHTMLOnly(object):
def __html__(self):
return Markup('<foo>')
class HasHTMLAndFormat(object):
def __html__(self):
return Markup('<foo>')
def __html_format__(self, spec):
return Markup('<FORMAT>')
assert Markup('{0}').format(HasHTMLOnly()) == Markup('<foo>')
assert Markup('{0}').format(HasHTMLAndFormat()) == Markup('<FORMAT>')
def test_complex_custom_formatting(self):
class User(object):
def __init__(self, id, username):
self.id = id
self.username = username
def __html_format__(self, format_spec):
if format_spec == 'link':
return Markup('<a href="/user/{0}">{1}</a>').format(
self.id,
self.__html__(),
)
elif format_spec:
raise ValueError('Invalid format spec')
return self.__html__()
def __html__(self):
return Markup('<span class=user>{0}</span>').format(self.username)
user = User(1, 'foo')
assert Markup('<p>User: {0:link}').format(user) == \
Markup('<p>User: <a href="/user/1"><span class=user>foo</span></a>')
def test_all_set(self):
import markupsafe as markup
for item in markup.__all__:
getattr(markup, item)
def test_escape_silent(self):
assert escape_silent(None) == Markup()
assert escape(None) == Markup(None)
assert escape_silent('<foo>') == Markup(u'<foo>')
def test_splitting(self):
self.assertEqual(Markup('a b').split(), [
Markup('a'),
Markup('b')
])
self.assertEqual(Markup('a b').rsplit(), [
Markup('a'),
Markup('b')
])
self.assertEqual(Markup('a\nb').splitlines(), [
Markup('a'),
Markup('b')
])
def test_mul(self):
self.assertEqual(Markup('a') * 3, Markup('aaa'))
class MarkupLeakTestCase(unittest.TestCase):
def test_markup_leaks(self):
counts = set()
for count in range(20):
for item in range(1000):
escape("foo")
escape("<foo>")
escape(u"foo")
escape(u"<foo>")
counts.add(len(gc.get_objects()))
assert len(counts) == 1, 'ouch, c extension seems to leak objects'
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(MarkupTestCase))
# this test only tests the c extension
if not hasattr(escape, 'func_code'):
suite.addTest(unittest.makeSuite(MarkupLeakTestCase))
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
# vim:sts=4:sw=4:et:
| 6,107 | Python | .py | 147 | 31.170068 | 82 | 0.51805 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,214 | _native.py | evilhero_mylar/lib/markupsafe/_native.py | # -*- coding: utf-8 -*-
"""
markupsafe._native
~~~~~~~~~~~~~~~~~~
Native Python implementation the C module is not compiled.
:copyright: (c) 2010 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from markupsafe import Markup
from markupsafe._compat import text_type
def escape(s):
"""Convert the characters &, <, >, ' and " in string s to HTML-safe
sequences. Use this if you need to display text that might contain
such characters in HTML. Marks return value as markup string.
"""
if hasattr(s, '__html__'):
return s.__html__()
return Markup(text_type(s)
.replace('&', '&')
.replace('>', '>')
.replace('<', '<')
.replace("'", ''')
.replace('"', '"')
)
def escape_silent(s):
"""Like :func:`escape` but converts `None` into an empty
markup string.
"""
if s is None:
return Markup()
return escape(s)
def soft_unicode(s):
"""Make a string unicode if it isn't already. That way a markup
string is not converted back to unicode.
"""
if not isinstance(s, text_type):
s = text_type(s)
return s
| 1,187 | Python | .py | 38 | 26.026316 | 71 | 0.599474 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,215 | autoProcessComics.py | evilhero_mylar/post-processing/autoProcessComics.py | import sys
import os.path
import ConfigParser
import urllib2
import urllib
import platform
try:
import requests
use_requests = True
except ImportError:
print '''Requests module not found on system. I'll revert so this will work, but you probably should install
requests to bypass this in the future (i.e. pip install requests)'''
use_requests = False
use_win32api = False
if platform.system() == 'Windows':
try:
import win32api
use_win32api = True
except ImportError:
print '''The win32api module was not found on this system. While it's fine to run without it, you're
running a Windows-based OS, so it would benefit you to install it. It enables ComicRN to better
work with file paths beyond the 260 character limit. Run "pip install pypiwin32".'''
apc_version = "2.04"
def processEpisode(dirName, nzbName=None):
print "Your ComicRN.py script is outdated. I'll force this through, but Failed Download Handling and possible enhancements/fixes will not work and could cause errors."
return processIssue(dirName, nzbName)
def processIssue(dirName, nzbName=None, failed=False, comicrn_version=None):
if use_win32api is True:
dirName = win32api.GetShortPathName(dirName)
config = ConfigParser.ConfigParser()
configFilename = os.path.join(os.path.dirname(sys.argv[0]), "autoProcessComics.cfg")
print "Loading config from", configFilename
if not os.path.isfile(configFilename):
print "ERROR: You need an autoProcessComics.cfg file - did you rename and edit the .sample?"
sys.exit(-1)
try:
fp = open(configFilename, "r")
config.readfp(fp)
fp.close()
except IOError, e:
print "Could not read configuration file: ", str(e)
sys.exit(1)
host = config.get("Mylar", "host")
port = config.get("Mylar", "port")
apikey = config.get("Mylar", "apikey")
if apikey is None:
print("No ApiKey has been set within Mylar to allow this script to run. This is NEW. Generate an API within Mylar, and make sure to enter the apikey value into the autoProcessComics.cfg file before re-running.")
sys.exit(1)
try:
ssl = int(config.get("Mylar", "ssl"))
except (ConfigParser.NoOptionError, ValueError):
ssl = 0
try:
web_root = config.get("Mylar", "web_root")
except ConfigParser.NoOptionError:
web_root = ""
if ssl:
protocol = "https://"
else:
protocol = "http://"
url = protocol + host + ":" + port + web_root + '/api'
params = {'cmd': 'forceProcess',
'apikey': apikey,
'nzb_folder': dirName}
if nzbName != None:
params['nzb_name'] = nzbName
params['failed'] = failed
params['apc_version'] = apc_version
params['comicrn_version'] = comicrn_version
if use_requests is True:
try:
print("Opening URL for post-process of %s @ %s/forceProcess:" % (dirName,url))
pp = requests.post(url, params=params, verify=False)
except Exception as e:
print("Unable to open URL: %s" %e)
sys.exit(1)
else:
print 'statuscode: %s' % pp.status_code
result = pp.content
print result
else:
url += "?" + urllib.urlencode(params)
print "Opening URL:", url
try:
urlObj = urllib2.urlopen(url)
except IOError, e:
print "Unable to open URL: ", str(e)
sys.exit(1)
else:
result = urlObj.readlines()
for line in result:
print line
if type(result) == list:
if any("Post Processing SUCCESSFUL" in s for s in result):
return 0
else:
return 1
else:
if any("Post Processing SUCCESSFUL" in s for s in result.split('\n')):
return 0
else:
return 1
| 3,958 | Python | .py | 102 | 31.098039 | 219 | 0.632196 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,216 | ComicRN.py | evilhero_mylar/post-processing/nzbget/ComicRN.py | #!/usr/bin/env python
#
##############################################################################
### NZBGET POST-PROCESSING SCRIPT ###
#
# Move and rename comics according to Mylar's autoProcessComics.cfg
#
# NOTE: This script requires Python to be installed on your system.
##############################################################################
### OPTIONS ###
### NZBGET POST-PROCESSING SCRIPT ###
##############################################################################
import sys, os
import autoProcessComics
comicrn_version = "1.01"
# NZBGet V11+
# Check if the script is called from nzbget 11.0 or later
if os.environ.has_key('NZBOP_SCRIPTDIR') and not os.environ['NZBOP_VERSION'][0:5] < '11.0':
# NZBGet argv: all passed as environment variables.
# Exit codes used by NZBGet
POSTPROCESS_PARCHECK=92
POSTPROCESS_SUCCESS=93
POSTPROCESS_ERROR=94
POSTPROCESS_NONE=95
#Start script
if os.environ['NZBOP_VERSION'][0:5] > '13.0':
if os.environ['NZBPP_TOTALSTATUS'] == 'FAILURE' or os.environ['NZBPP_TOTALSTATUS'] == 'WARNING':
failit = 1
else:
failit = 0
else:
#NZBPP_TOTALSTATUS only exists in 13.0 - so if it's not that but greater than 11.0+, we need to use NZBPP_STATUS
#assume failit = 1 (failed) by default
failit = 1
if os.environ['NZBPP_PARSTATUS'] == '1' or os.environ['NZBPP_UNPACKSTATUS'] == '1':
print 'Download of "%s" has failed.' % (os.environ['NZBPP_NZBNAME'])
elif os.environ['NZBPP_UNPACKSTATUS'] in ('3', '4'):
print 'Download of "%s" has failed.' % (os.environ['NZBPP_NZBNAME'])
elif os.environ['NZBPP_PARSTATUS'] == '4':
print 'Download of "%s" requires par-repair.' % (os.environ['NZBPP_NZBNAME'])
else:
print 'Download of "%s" has successfully completed.' % (os.environ['NZBPP_NZBNAME'])
failit = 0
result = autoProcessComics.processIssue(os.environ['NZBPP_DIRECTORY'], os.environ['NZBPP_NZBNAME'], failed=failit, comicrn_version=comicrn_version)
elif len(sys.argv) == NZBGET_NO_OF_ARGUMENTS:
result = autoProcessComics.processIssue(sys.argv[1], sys.argv[2], sys.argv[3], comicrn_version=comicrn_version)
if result == 0:
if os.environ.has_key('NZBOP_SCRIPTDIR'): # log success for nzbget
sys.exit(POSTPROCESS_SUCCESS)
else:
if os.environ.has_key('NZBOP_SCRIPTDIR'): # log fail for nzbget
sys.exit(POSTPROCESS_ERROR)
| 2,658 | Python | .py | 52 | 45.230769 | 151 | 0.569213 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,217 | ComicRN.py | evilhero_mylar/post-processing/sabnzbd/ComicRN.py | #!/usr/bin/env python
#
##############################################################################
### SABNZBD POST-PROCESSING SCRIPT ###
#
# Move and rename comics according to Mylar's autoProcessComics.cfg
#
# NOTE: This script requires Python to be installed on your system.
##############################################################################
#module loading
import sys
import autoProcessComics
comicrn_version = "1.01"
#the code.
if len(sys.argv) < 2:
print "No folder supplied - is this being called from SABnzbd or NZBGet?"
sys.exit()
elif len(sys.argv) >= 3:
sys.exit(autoProcessComics.processIssue(sys.argv[1], sys.argv[3], sys.argv[7], comicrn_version=comicrn_version))
else:
sys.exit(autoProcessComics.processIssue(sys.argv[1], comicrn_version=comicrn_version))
| 847 | Python | .py | 21 | 38.380952 | 116 | 0.579075 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,218 | notifiers.py | evilhero_mylar/mylar/notifiers.py | # This file is part of mylar.
#
# mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with mylar. If not, see <http://www.gnu.org/licenses/>.
from mylar import logger
import base64
import cherrypy
import urllib
import urllib2
import mylar
from httplib import HTTPSConnection
from urllib import urlencode
import os.path
import subprocess
import time
import simplejson
import json
import requests
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate, make_msgid
# This was obviously all taken from headphones with great appreciation :)
class PROWL:
keys = []
priority = []
def __init__(self):
self.enabled = mylar.CONFIG.PROWL_ENABLED
self.keys = mylar.CONFIG.PROWL_KEYS
self.priority = mylar.CONFIG.PROWL_PRIORITY
pass
def conf(self, options):
return cherrypy.config['config'].get('Prowl', options)
def notify(self, message, event, module=None):
if not mylar.CONFIG.PROWL_ENABLED:
return
if module is None:
module = ''
module += '[NOTIFIER]'
http_handler = HTTPSConnection("api.prowlapp.com")
data = {'apikey': mylar.CONFIG.PROWL_KEYS,
'application': 'Mylar',
'event': event,
'description': message.encode("utf-8"),
'priority': mylar.CONFIG.PROWL_PRIORITY}
http_handler.request("POST",
"/publicapi/add",
headers = {'Content-type': "application/x-www-form-urlencoded"},
body = urlencode(data))
response = http_handler.getresponse()
request_status = response.status
if request_status == 200:
logger.info(module + ' Prowl notifications sent.')
return True
elif request_status == 401:
logger.info(module + ' Prowl auth failed: %s' % response.reason)
return False
else:
logger.info(module + ' Prowl notification failed.')
return False
def test_notify(self):
self.notify('ZOMG Lazors Pewpewpew!', 'Test Message')
# 2013-04-01 Added Pushover.net notifications, based on copy of Prowl class above.
# No extra care has been put into API friendliness at the moment (read: https://pushover.net/api#friendly)
class PUSHOVER:
def __init__(self, test_apikey=None, test_userkey=None, test_device=None):
if all([test_apikey is None, test_userkey is None, test_device is None]):
self.PUSHOVER_URL = 'https://api.pushover.net/1/messages.json'
self.test = False
else:
self.PUSHOVER_URL = 'https://api.pushover.net/1/users/validate.json'
self.test = True
self.enabled = mylar.CONFIG.PUSHOVER_ENABLED
if test_apikey is None:
if mylar.CONFIG.PUSHOVER_APIKEY is None or mylar.CONFIG.PUSHOVER_APIKEY == 'None':
logger.warn('No Pushover Apikey is present. Fix it')
return False
else:
self.apikey = mylar.CONFIG.PUSHOVER_APIKEY
else:
self.apikey = test_apikey
if test_device is None:
self.device = mylar.CONFIG.PUSHOVER_DEVICE
else:
self.device = test_device
if test_userkey is None:
self.userkey = mylar.CONFIG.PUSHOVER_USERKEY
else:
self.userkey = test_userkey
self.priority = mylar.CONFIG.PUSHOVER_PRIORITY
self._session = requests.Session()
self._session.headers = {'Content-type': "application/x-www-form-urlencoded"}
def notify(self, event, message=None, snatched_nzb=None, prov=None, sent_to=None, module=None):
if module is None:
module = ''
module += '[NOTIFIER]'
if snatched_nzb:
if snatched_nzb[-1] == '\.':
snatched_nzb = snatched_nzb[:-1]
message = "Mylar has snatched: " + snatched_nzb + " from " + prov + " and " + sent_to
data = {'token': mylar.CONFIG.PUSHOVER_APIKEY,
'user': mylar.CONFIG.PUSHOVER_USERKEY,
'message': message.encode("utf-8"),
'title': event,
'priority': mylar.CONFIG.PUSHOVER_PRIORITY}
if all([self.device is not None, self.device != 'None']):
data.update({'device': self.device})
r = self._session.post(self.PUSHOVER_URL, data=data, verify=True)
if r.status_code == 200:
try:
response = r.json()
if 'devices' in response and self.test is True:
logger.fdebug('%s Available devices: %s' % (module, response))
if any([self.device is None, self.device == 'None']):
self.device = 'all available devices'
r = self._session.post('https://api.pushover.net/1/messages.json', data=data, verify=True)
if r.status_code == 200:
logger.info('%s PushOver notifications sent to %s.' % (module, self.device))
elif r.status_code >=400 and r.status_code < 500:
logger.error('%s PushOver request failed to %s: %s' % (module, self.device, r.content))
return False
else:
logger.error('%s PushOver notification failed serverside.' % module)
return False
else:
logger.info('%s PushOver notifications sent.' % module)
except Exception as e:
logger.warn('%s[ERROR] - %s' % (module, e))
return False
else:
return True
elif r.status_code >= 400 and r.status_code < 500:
logger.error('%s PushOver request failed: %s' % (module, r.content))
return False
else:
logger.error('%s PushOver notification failed serverside.' % module)
return False
def test_notify(self):
return self.notify(event='Test Message', message='Release the Ninjas!')
class BOXCAR:
#new BoxCar2 API
def __init__(self):
self.url = 'https://new.boxcar.io/api/notifications'
def _sendBoxcar(self, msg, title, module):
"""
Sends a boxcar notification to the address provided
msg: The message to send (unicode)
title: The title of the message
returns: True if the message succeeded, False otherwise
"""
try:
data = urllib.urlencode({
'user_credentials': mylar.CONFIG.BOXCAR_TOKEN,
'notification[title]': title.encode('utf-8').strip(),
'notification[long_message]': msg.encode('utf-8'),
'notification[sound]': "done"
})
req = urllib2.Request(self.url)
handle = urllib2.urlopen(req, data)
handle.close()
return True
except urllib2.URLError, e:
# if we get an error back that doesn't have an error code then who knows what's really happening
if not hasattr(e, 'code'):
logger.error(module + 'Boxcar2 notification failed. %s' % e)
# If you receive an HTTP status code of 400, it is because you failed to send the proper parameters
elif e.code == 400:
logger.info(module + ' Wrong data sent to boxcar')
logger.info(module + ' data:' + data)
else:
logger.error(module + ' Boxcar2 notification failed. Error code: ' + str(e.code))
return False
logger.fdebug(module + ' Boxcar2 notification successful.')
return True
def notify(self, prline=None, prline2=None, sent_to=None, snatched_nzb=None, force=False, module=None, snline=None):
"""
Sends a boxcar notification based on the provided info or SB config
title: The title of the notification to send
message: The message string to send
force: If True then the notification will be sent even if Boxcar is disabled in the config
"""
if module is None:
module = ''
module += '[NOTIFIER]'
if not mylar.CONFIG.BOXCAR_ENABLED and not force:
logger.fdebug(module + ' Notification for Boxcar not enabled, skipping this notification.')
return False
# if no username was given then use the one from the config
if snatched_nzb:
title = snline
message = "Mylar has snatched: " + snatched_nzb + " and " + sent_to
else:
title = prline
message = prline2
logger.info(module + ' Sending notification to Boxcar2')
self._sendBoxcar(message, title, module)
return True
def test_notify(self):
self.notify(prline='Test Message',prline2='ZOMG Lazors Pewpewpew!')
class PUSHBULLET:
def __init__(self, test_apikey=None):
self.PUSH_URL = "https://api.pushbullet.com/v2/pushes"
if test_apikey is None:
self.apikey = mylar.CONFIG.PUSHBULLET_APIKEY
else:
self.apikey = test_apikey
self.deviceid = mylar.CONFIG.PUSHBULLET_DEVICEID
self.channel_tag = mylar.CONFIG.PUSHBULLET_CHANNEL_TAG
self._json_header = {'Content-Type': 'application/json',
'Authorization': 'Basic %s' % base64.b64encode(self.apikey + ":")}
self._session = requests.Session()
self._session.headers.update(self._json_header)
def get_devices(self, api):
return self.notify(method="GET")
def notify(self, snline=None, prline=None, prline2=None, snatched=None, sent_to=None, prov=None, module=None, method=None):
if module is None:
module = ''
module += '[NOTIFIER]'
# http_handler = HTTPSConnection("api.pushbullet.com")
# if method == 'GET':
# uri = '/v2/devices'
# else:
# method = 'POST'
# uri = '/v2/pushes'
# authString = base64.b64encode(self.apikey + ":")
if method == 'GET':
pass
# http_handler.request(method, uri, None, headers={'Authorization': 'Basic %s:' % authString})
else:
if snatched:
if snatched[-1] == '.': snatched = snatched[:-1]
event = snline
message = "Mylar has snatched: " + snatched + " from " + prov + " and " + sent_to
else:
event = prline + ' complete!'
message = prline2
data = {'type': "note", #'device_iden': self.deviceid,
'title': event.encode('utf-8'), #"mylar",
'body': message.encode('utf-8')}
if self.channel_tag:
data['channel_tag'] = self.channel_tag
r = self._session.post(self.PUSH_URL, data=json.dumps(data))
dt = r.json()
if r.status_code == 200:
if method == 'GET':
return dt
else:
logger.info(module + ' PushBullet notifications sent.')
return {'status': True,
'message': 'APIKEY verified OK / notification sent'}
elif r.status_code >= 400 and r.status_code < 500:
logger.error(module + ' PushBullet request failed: %s' % r.content)
return {'status': False,
'message': '[' + str(r.status_code) + '] ' + dt['error']['message']}
else:
logger.error(module + ' PushBullet notification failed serverside: %s' % r.content)
return {'status': False,
'message': '[' + str(r.status_code) + '] ' + dt['error']['message']}
def test_notify(self):
return self.notify(prline='Test Message', prline2='Release the Ninjas!')
class TELEGRAM:
def __init__(self, test_userid=None, test_token=None):
self.TELEGRAM_API = "https://api.telegram.org/bot%s/%s"
if test_userid is None:
self.userid = mylar.CONFIG.TELEGRAM_USERID
else:
self.userid = test_userid
if test_token is None:
self.token = mylar.CONFIG.TELEGRAM_TOKEN
else:
self.token = test_token
def notify(self, message, imageUrl=None):
# Construct message
payload = {'chat_id': self.userid, 'text': message}
sendMethod = "sendMessage"
if imageUrl:
# Construct message
payload = {'chat_id': self.userid, 'caption': message, 'photo': imageUrl}
sendMethod = "sendPhoto"
# Send message to user using Telegram's Bot API
try:
response = requests.post(self.TELEGRAM_API % (self.token, sendMethod), json=payload, verify=True)
except Exception as e:
logger.info('Telegram notify failed: ' + str(e))
# Error logging
sent_successfully = True
if not response.status_code == 200:
logger.info(u'Could not send notification to TelegramBot (token=%s). Response: [%s]' % (self.token, response.text))
sent_successfully = False
if not sent_successfully and sendMethod != "sendMessage":
return self.notify(message)
logger.info(u"Telegram notifications sent.")
return sent_successfully
def test_notify(self):
return self.notify('Test Message: Release the Ninjas!')
class EMAIL:
def __init__(self, test_emailfrom=None, test_emailto=None, test_emailsvr=None, test_emailport=None, test_emailuser=None, test_emailpass=None, test_emailenc=None):
self.emailfrom = mylar.CONFIG.EMAIL_FROM if test_emailfrom is None else test_emailfrom
self.emailto = mylar.CONFIG.EMAIL_TO if test_emailto is None else test_emailto
self.emailsvr = mylar.CONFIG.EMAIL_SERVER if test_emailsvr is None else test_emailsvr
self.emailport = mylar.CONFIG.EMAIL_PORT if test_emailport is None else test_emailport
self.emailuser = mylar.CONFIG.EMAIL_USER if test_emailuser is None else test_emailuser
self.emailpass = mylar.CONFIG.EMAIL_PASSWORD if test_emailpass is None else test_emailpass
self.emailenc = mylar.CONFIG.EMAIL_ENC if test_emailenc is None else int(test_emailenc)
def notify(self, message, subject, module=None):
if module is None:
module = ''
module += '[NOTIFIER]'
sent_successfully = False
try:
logger.debug(module + u' Sending email notification. From: [%s] - To: [%s] - Server: [%s] - Port: [%s] - Username: [%s] - Password: [********] - Encryption: [%s] - Message: [%s]' % (self.emailfrom, self.emailto, self.emailsvr, self.emailport, self.emailuser, self.emailenc, message))
msg = MIMEMultipart()
msg['From'] = str(self.emailfrom)
msg['To'] = str(self.emailto)
msg['Subject'] = subject
msg['Date'] = formatdate()
msg['Message-ID'] = make_msgid('mylar')
msg.attach(MIMEText(message, 'plain'))
if self.emailenc is 1:
sock = smtplib.SMTP_SSL(self.emailsvr, str(self.emailport))
else:
sock = smtplib.SMTP(self.emailsvr, str(self.emailport))
if self.emailenc is 2:
sock.starttls()
if self.emailuser or self.emailpass:
sock.login(str(self.emailuser), str(self.emailpass))
sock.sendmail(str(self.emailfrom), str(self.emailto), msg.as_string())
sock.quit()
sent_successfully = True
except Exception, e:
logger.warn(module + u' Oh no!! Email notification failed: ' + str(e))
return sent_successfully
def test_notify(self):
return self.notify('Test Message: With great power comes great responsibility.', 'Mylar notification - Test')
class SLACK:
def __init__(self, test_webhook_url=None):
self.webhook_url = mylar.CONFIG.SLACK_WEBHOOK_URL if test_webhook_url is None else test_webhook_url
def notify(self, text, attachment_text, snatched_nzb=None, prov=None, sent_to=None, module=None):
if module is None:
module = ''
module += '[NOTIFIER]'
if 'snatched' in attachment_text.lower():
snatched_text = '%s: %s' % (attachment_text, snatched_nzb)
if all([sent_to is not None, prov is not None]):
snatched_text += ' from %s and %s' % (prov, sent_to)
elif sent_to is None:
snatched_text += ' from %s' % prov
attachment_text = snatched_text
else:
pass
payload = {
# "text": text,
# "attachments": [
# {
# "color": "#36a64f",
# "text": attachment_text
# }
# ]
# FIX: #1861 move notif from attachment to msg body - bbq
"text": attachment_text
}
try:
response = requests.post(self.webhook_url, json=payload, verify=True)
except Exception, e:
logger.info(module + u'Slack notify failed: ' + str(e))
# Error logging
sent_successfuly = True
if not response.status_code == 200:
logger.info(module + u'Could not send notification to Slack (webhook_url=%s). Response: [%s]' % (self.webhook_url, response.text))
sent_successfuly = False
logger.info(module + u"Slack notifications sent.")
return sent_successfuly
def test_notify(self):
return self.notify('Test Message', 'Release the Ninjas!')
| 18,324 | Python | .py | 384 | 37.033854 | 295 | 0.593818 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,219 | db.py | evilhero_mylar/mylar/db.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
#####################################
## Stolen from Sick-Beard's db.py ##
#####################################
from __future__ import with_statement
import os
import sqlite3
import threading
import time
import Queue
import mylar
import logger
db_lock = threading.Lock()
mylarQueue = Queue.Queue()
def dbFilename(filename="mylar.db"):
return os.path.join(mylar.DATA_DIR, filename)
class WriteOnly:
def __init__(self):
t = threading.Thread(target=self.worker, name="DB-WRITER")
t.daemon = True
t.start()
logger.fdebug('Thread WriteOnly initialized.')
def worker(self):
myDB = DBConnection()
#this should be in it's own thread somewhere, constantly polling the queue and sending them to the writer.
logger.fdebug('worker started.')
while True:
thisthread = threading.currentThread().name
if not mylarQueue.empty():
# Rename the main thread
logger.fdebug('[' + str(thisthread) + '] queue is not empty yet...')
(QtableName, QvalueDict, QkeyDict) = mylarQueue.get(block=True, timeout=None)
logger.fdebug('[REQUEUE] Table: ' + str(QtableName) + ' values: ' + str(QvalueDict) + ' keys: ' + str(QkeyDict))
sqlResult = myDB.upsert(QtableName, QvalueDict, QkeyDict)
if sqlResult:
mylarQueue.task_done()
return sqlResult
else:
time.sleep(1)
#logger.fdebug('[' + str(thisthread) + '] sleeping until active.')
class DBConnection:
def __init__(self, filename="mylar.db"):
self.filename = filename
self.connection = sqlite3.connect(dbFilename(filename), timeout=20)
self.connection.row_factory = sqlite3.Row
self.queue = mylarQueue
def fetch(self, query, args=None):
with db_lock:
if query == None:
return
sqlResult = None
attempt = 0
while attempt < 5:
try:
if args == None:
#logger.fdebug("[FETCH] : " + query)
cursor = self.connection.cursor()
sqlResult = cursor.execute(query)
else:
#logger.fdebug("[FETCH] : " + query + " with args " + str(args))
cursor = self.connection.cursor()
sqlResult = cursor.execute(query, args)
# get out of the connection attempt loop since we were successful
break
except sqlite3.OperationalError, e:
if "unable to open database file" in e.args[0] or "database is locked" in e.args[0]:
logger.warn('Database Error: %s' % e)
attempt += 1
time.sleep(1)
else:
logger.warn('DB error: %s' % e)
raise
except sqlite3.DatabaseError, e:
logger.error('Fatal error executing query: %s' % e)
raise
return sqlResult
def action(self, query, args=None):
with db_lock:
if query == None:
return
sqlResult = None
attempt = 0
while attempt < 5:
try:
if args == None:
#logger.fdebug("[ACTION] : " + query)
sqlResult = self.connection.execute(query)
else:
#logger.fdebug("[ACTION] : " + query + " with args " + str(args))
sqlResult = self.connection.execute(query, args)
self.connection.commit()
break
except sqlite3.OperationalError, e:
if "unable to open database file" in e.message or "database is locked" in e.message:
logger.warn('Database Error: %s' % e)
logger.warn('sqlresult: %s' % query)
attempt += 1
time.sleep(1)
else:
logger.error('Database error executing %s :: %s' % (query, e))
raise
return sqlResult
def select(self, query, args=None):
sqlResults = self.fetch(query, args).fetchall()
if sqlResults == None:
return []
return sqlResults
def selectone(self, query, args=None):
sqlResults = self.fetch(query, args)
if sqlResults == None:
return []
return sqlResults
def upsert(self, tableName, valueDict, keyDict):
thisthread = threading.currentThread().name
changesBefore = self.connection.total_changes
genParams = lambda myDict: [x + " = ?" for x in myDict.keys()]
query = "UPDATE " + tableName + " SET " + ", ".join(genParams(valueDict)) + " WHERE " + " AND ".join(genParams(keyDict))
self.action(query, valueDict.values() + keyDict.values())
if self.connection.total_changes == changesBefore:
query = "INSERT INTO " +tableName +" (" + ", ".join(valueDict.keys() + keyDict.keys()) + ")" + \
" VALUES (" + ", ".join(["?"] * len(valueDict.keys() + keyDict.keys())) + ")"
self.action(query, valueDict.values() + keyDict.values())
#else:
# logger.info('[' + str(thisthread) + '] db is currently locked for writing. Queuing this action until it is free')
# logger.info('Table: ' + str(tableName) + ' Values: ' + str(valueDict) + ' Keys: ' + str(keyDict))
# self.queue.put( (tableName, valueDict, keyDict) )
# #assuming this is coming in from a seperate thread, so loop it until it's free to write.
# #self.queuesend()
| 6,615 | Python | .py | 141 | 34.468085 | 128 | 0.548974 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,220 | webviewer.py | evilhero_mylar/mylar/webviewer.py | import os
import re
import cherrypy
import stat
import zipfile
from lib.rarfile import rarfile
import mylar
try:
from PIL import Image
except ImportError:
logger.debug("WebReader Requested, but PIL or pillow libraries must be installed. Please execute 'pip install pillow', then restart Mylar.")
return serve_template(templatename="index.html", title="Home", comics=comics, alphaindex=mylar.CONFIG.ALPHAINDEX)
from mylar import logger, db, importer, mb, search, filechecker, helpers, updater, parseit, weeklypull, librarysync, moveit, Failed, readinglist, config
from mylar.webserve import serve_template
class WebViewer(object):
def __init__(self):
self.ish_id = None
self.page_num = None
self.kwargs = None
self.data = None
if not os.path.exists(os.path.join(mylar.DATA_DIR, 'sessions')):
os.makedirs(os.path.abspath(os.path.join(mylar.DATA_DIR, 'sessions')))
updatecherrypyconf = {
'tools.gzip.on': True,
'tools.gzip.mime_types': ['text/*', 'application/*', 'image/*'],
'tools.sessions.timeout': 1440,
'tools.sessions.storage_class': cherrypy.lib.sessions.FileSession,
'tools.sessions.storage_path': os.path.join(mylar.DATA_DIR, "sessions"),
'request.show_tracebacks': False,
'engine.timeout_monitor.on': False,
}
if mylar.CONFIG.HTTP_PASSWORD is None:
updatecherrypyconf.update({
'tools.sessions.on': True,
})
cherrypy.config.update(updatecherrypyconf)
cherrypy.engine.signals.subscribe()
def read_comic(self, ish_id = None, page_num = None, size = None):
logger.debug("WebReader Requested, looking for ish_id %s and page_num %s" % (ish_id, page_num))
if size == None:
user_size_pref = 'wide'
else:
user_size_pref = size
try:
ish_id
except:
logger.warn("WebReader: ish_id not set!")
myDB = db.DBConnection()
comic = myDB.selectone('select comics.ComicLocation, issues.Location from comics, issues where comics.comicid = issues.comicid and issues.issueid = ?' , [ish_id]).fetchone()
if comic is None:
logger.warn("WebReader: ish_id %s requested but not in the database!" % ish_id)
raise cherrypy.HTTPRedirect("home")
# cherrypy.config.update()
comic_path = os.path.join(comic['ComicLocation'], comic['Location'])
logger.debug("WebReader found ish_id %s at %s" % (ish_id, comic_path))
# cherrypy.session['ish_id'].load()
# if 'sizepref' not in cherrypy.session:
# cherrypy.session['sizepref'] = user_size_pref
# user_size_pref = cherrypy.session['sizepref']
# logger.debug("WebReader setting user_size_pref to %s" % user_size_pref)
scanner = ComicScanner()
image_list = scanner.reading_images(ish_id)
logger.debug("Image list contains %s pages" % (len(image_list)))
if len(image_list) == 0:
logger.debug("Unpacking ish_id %s from comic_path %s" % (ish_id, comic_path))
scanner.user_unpack_comic(ish_id, comic_path)
else:
logger.debug("ish_id %s already unpacked." % ish_id)
num_pages = len(image_list)
logger.debug("Found %s pages for ish_id %s from comic_path %s" % (num_pages, ish_id, comic_path))
if num_pages == 0:
image_list = ['images/skipped_icon.png']
cookie_comic = re.sub(r'\W+', '', comic_path)
cookie_comic = "wv_" + cookie_comic.decode('unicode_escape')
logger.debug("about to drop a cookie for " + cookie_comic + " which represents " + comic_path)
cookie_check = cherrypy.request.cookie
if cookie_comic not in cookie_check:
logger.debug("Cookie Creation")
cookie_path = '/'
cookie_maxage = '2419200'
cookie_set = cherrypy.response.cookie
cookie_set['cookie_comic'] = 0
cookie_set['cookie_comic']['path'] = cookie_path.decode('unicode_escape')
cookie_set['cookie_comic']['max-age'] = cookie_maxage.decode('unicode_escape')
next_page = page_num + 1
prev_page = page_num - 1
else:
logger.debug("Cookie Read")
page_num = int(cherrypy.request.cookie['cookie_comic'].value)
logger.debug("Cookie Set To %d" % page_num)
next_page = page_num + 1
prev_page = page_num - 1
logger.info("Reader Served")
logger.debug("Serving comic " + comic['Location'] + " page number " + str(page_num))
return serve_template(templatename="read.html", pages=image_list, current_page=page_num, np=next_page, pp=prev_page, nop=num_pages, size=user_size_pref, cc=cookie_comic, comicpath=comic_path, ish_id=ish_id)
def up_size_pref(self, pref):
cherrypy.session.load()
cherrypy.session['sizepref'] = pref
cherrypy.session.save()
return
class ComicScanner(object):
# This method will handle scanning the directories and returning a list of them all.
def dir_scan(self):
logger.debug("Dir Scan Requested")
full_paths = []
full_paths.append(mylar.CONFIG.DESTINATION_DIR)
for root, dirs, files in os.walk(mylar.CONFIG.DESTINATION_DIR):
full_paths.extend(os.path.join(root, d) for d in dirs)
logger.info("Dir Scan Completed")
logger.info("%i Dirs Found" % (len(full_paths)))
return full_paths
def user_unpack_comic(self, ish_id, comic_path):
logger.info("%s unpack requested" % comic_path)
for root, dirs, files in os.walk(os.path.join(mylar.CONFIG.CACHE_DIR, "webviewer", ish_id), topdown=False):
for f in files:
os.chmod(os.path.join(root, f), stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # 0777
os.remove(os.path.join(root, f))
for root, dirs, files in os.walk(os.path.join(mylar.CONFIG.CACHE_DIR, "webviewer", ish_id), topdown=False):
for d in dirs:
os.chmod(os.path.join(root, d), stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # 0777
os.rmdir(os.path.join(root, d))
if comic_path.endswith(".cbr"):
opened_rar = rarfile.RarFile(comic_path)
opened_rar.extractall(os.path.join(mylar.CONFIG.CACHE_DIR, "webviewer", ish_id))
elif comic_path.endswith(".cbz"):
opened_zip = zipfile.ZipFile(comic_path)
opened_zip.extractall(os.path.join(mylar.CONFIG.CACHE_DIR, "webviewer", ish_id))
return
# This method will return a list of .jpg files in their numberical order to be fed into the reading view.
def reading_images(self, ish_id):
logger.debug("Image List Requested")
image_list = []
image_src = os.path.join(mylar.CONFIG.CACHE_DIR, "webviewer", ish_id)
image_loc = os.path.join(mylar.CONFIG.HTTP_ROOT, 'cache', "webviewer", ish_id)
for root, dirs, files in os.walk(image_src):
for f in files:
if f.endswith((".png", ".gif", ".bmp", ".dib", ".jpg", ".jpeg", ".jpe", ".jif", ".jfif", ".jfi", ".tiff", ".tif")):
image_list.append( os.path.join(image_loc, f) )
image_list.sort()
logger.debug("Image List Created")
return image_list
| 7,537 | Python | .py | 141 | 43.347518 | 214 | 0.618664 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,221 | cmtagmylar.py | evilhero_mylar/mylar/cmtagmylar.py | # This script was taken almost entirely from Manders2600 Script with the use of the awesome ComicTagger.
# modified very slightly so Mylar just passes it the IssueID for it to do it's magic.
import os, errno
import sys
import re
import glob
import shlex
import platform
import shutil
import time
import zipfile
import subprocess
from subprocess import CalledProcessError, check_output
import mylar
from mylar import logger
def run(dirName, nzbName=None, issueid=None, comversion=None, manual=None, filename=None, module=None, manualmeta=False):
if module is None:
module = ''
module += '[META-TAGGER]'
logger.fdebug(module + ' dirName:' + dirName)
# 2015-11-23: Recent CV API changes restrict the rate-limit to 1 api request / second.
# ComicTagger has to be included now with the install as a timer had to be added to allow for the 1/second rule.
comictagger_cmd = os.path.join(mylar.CMTAGGER_PATH, 'comictagger.py')
logger.fdebug('ComicTagger Path location for internal comictagger.py set to : ' + comictagger_cmd)
# Force mylar to use cmtagger_path = mylar.PROG_DIR to force the use of the included lib.
logger.fdebug(module + ' Filename is : ' + filename)
filepath = filename
og_filepath = filepath
try:
filename = os.path.split(filename)[1] # just the filename itself
except:
logger.warn('Unable to detect filename within directory - I am aborting the tagging. You best check things out.')
return "fail"
#make use of temporary file location in order to post-process this to ensure that things don't get hammered when converting
new_filepath = None
new_folder = None
try:
import tempfile
logger.fdebug('Filepath: %s' %filepath)
logger.fdebug('Filename: %s' %filename)
new_folder = tempfile.mkdtemp(prefix='mylar_', dir=mylar.CONFIG.CACHE_DIR) #prefix, suffix, dir
logger.fdebug('New_Folder: %s' % new_folder)
new_filepath = os.path.join(new_folder, filename)
logger.fdebug('New_Filepath: %s' % new_filepath)
if mylar.CONFIG.FILE_OPTS == 'copy' and manualmeta == False:
shutil.copy(filepath, new_filepath)
else:
shutil.copy(filepath, new_filepath)
filepath = new_filepath
except Exception as e:
logger.warn('%s Unexpected Error: %s [%s]' % (module, sys.exc_info()[0], e))
logger.warn(module + ' Unable to create temporary directory to perform meta-tagging. Processing without metatagging.')
tidyup(og_filepath, new_filepath, new_folder, manualmeta)
return "fail"
## Sets up other directories ##
scriptname = os.path.basename(sys.argv[0])
downloadpath = os.path.abspath(dirName)
sabnzbdscriptpath = os.path.dirname(sys.argv[0])
comicpath = new_folder
logger.fdebug(module + ' Paths / Locations:')
logger.fdebug(module + ' scriptname : ' + scriptname)
logger.fdebug(module + ' downloadpath : ' + downloadpath)
logger.fdebug(module + ' sabnzbdscriptpath : ' + sabnzbdscriptpath)
logger.fdebug(module + ' comicpath : ' + comicpath)
logger.fdebug(module + ' Running the ComicTagger Add-on for Mylar')
##set up default comictagger options here.
#used for cbr - to - cbz conversion
#depending on copy/move - eitehr we retain the rar or we don't.
if mylar.CONFIG.FILE_OPTS == 'move':
cbr2cbzoptions = ["-e", "--delete-rar"]
else:
cbr2cbzoptions = ["-e"]
tagoptions = ["-s"]
if mylar.CONFIG.CMTAG_VOLUME:
if mylar.CONFIG.CMTAG_START_YEAR_AS_VOLUME:
comversion = str(comversion)
else:
if any([comversion is None, comversion == '', comversion == 'None']):
comversion = '1'
comversion = re.sub('[^0-9]', '', comversion).strip()
cvers = 'volume=' + str(comversion)
else:
cvers = "volume="
tagoptions.extend(["-m", cvers])
try:
ctversion = subprocess.check_output([sys.executable, comictagger_cmd, "--version"], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
#logger.warn(module + "[WARNING] "command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))
logger.warn(module + '[WARNING] Make sure that you are using the comictagger included with Mylar.')
tidyup(filepath, new_filepath, new_folder, manualmeta)
return "fail"
ctend = ctversion.find('\n')
ctcheck = re.sub("[^0-9]", "", ctversion[:ctend])
ctcheck = re.sub('\.', '', ctcheck).strip()
if int(ctcheck) >= int('1115'): # (v1.1.15)
if any([mylar.CONFIG.COMICVINE_API == 'None', mylar.CONFIG.COMICVINE_API is None]):
logger.fdebug(module + ' ' + ctversion[:ctend] + ' being used - no personal ComicVine API Key supplied. Take your chances.')
use_cvapi = "False"
else:
logger.fdebug(module + ' ' + ctversion[:ctend] + ' being used - using personal ComicVine API key supplied via mylar.')
use_cvapi = "True"
tagoptions.extend(["--cv-api-key", mylar.CONFIG.COMICVINE_API])
else:
logger.fdebug(module + ' ' + ctversion[:ctend+1] + ' being used - personal ComicVine API key not supported in this version. Good luck.')
use_cvapi = "False"
i = 1
tagcnt = 0
if mylar.CONFIG.CT_TAG_CR:
tagcnt = 1
logger.fdebug(module + ' CR Tagging enabled.')
if mylar.CONFIG.CT_TAG_CBL:
if not mylar.CONFIG.CT_TAG_CR: i = 2 #set the tag to start at cbl and end without doing another tagging.
tagcnt = 2
logger.fdebug(module + ' CBL Tagging enabled.')
if tagcnt == 0:
logger.warn(module + ' You have metatagging enabled, but you have not selected the type(s) of metadata to write. Please fix and re-run manually')
tidyup(filepath, new_filepath, new_folder, manualmeta)
return "fail"
#if it's a cbz file - check if no-overwrite existing tags is enabled / disabled in config.
if filename.endswith('.cbz'):
if mylar.CONFIG.CT_CBZ_OVERWRITE:
logger.fdebug(module + ' Will modify existing tag blocks even if it exists.')
else:
logger.fdebug(module + ' Will NOT modify existing tag blocks even if they exist already.')
tagoptions.extend(["--nooverwrite"])
if issueid is None:
tagoptions.extend(["-f", "-o"])
else:
tagoptions.extend(["-o", "--id", issueid])
original_tagoptions = tagoptions
og_tagtype = None
initial_ctrun = True
error_remove = False
while (i <= tagcnt):
if initial_ctrun:
f_tagoptions = cbr2cbzoptions
f_tagoptions.extend([filepath])
else:
if i == 1:
tagtype = 'cr' # CR meta-tagging cycle.
tagdisp = 'ComicRack tagging'
elif i == 2:
tagtype = 'cbl' # Cbl meta-tagging cycle
tagdisp = 'Comicbooklover tagging'
f_tagoptions = original_tagoptions
if og_tagtype is not None:
for index, item in enumerate(f_tagoptions):
if item == og_tagtype:
f_tagoptions[index] = tagtype
else:
f_tagoptions.extend(["--type", tagtype, filepath])
og_tagtype = tagtype
logger.info(module + ' ' + tagdisp + ' meta-tagging processing started.')
currentScriptName = [sys.executable, comictagger_cmd]
script_cmd = currentScriptName + f_tagoptions
if initial_ctrun:
logger.fdebug(module + ' Enabling ComicTagger script: ' + str(currentScriptName) + ' with options: ' + str(f_tagoptions))
script_cmdlog = script_cmd
else:
logger.fdebug(module + ' Enabling ComicTagger script: ' + str(currentScriptName) + ' with options: ' + re.sub(f_tagoptions[f_tagoptions.index(mylar.CONFIG.COMICVINE_API)], 'REDACTED', str(f_tagoptions)))
# generate a safe command line string to execute the script and provide all the parameters
script_cmdlog = re.sub(f_tagoptions[f_tagoptions.index(mylar.CONFIG.COMICVINE_API)], 'REDACTED', str(script_cmd))
logger.fdebug(module + ' Executing command: ' +str(script_cmdlog))
logger.fdebug(module + ' Absolute path to script: ' +script_cmd[0])
try:
# use subprocess to run the command and capture output
p = subprocess.Popen(script_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, err = p.communicate()
#logger.info(out)
#logger.info(err)
if initial_ctrun and 'exported successfully' in out:
logger.fdebug(module + '[COMIC-TAGGER] : ' +str(out))
#Archive exported successfully to: X-Men v4 008 (2014) (Digital) (Nahga-Empire).cbz (Original deleted)
if 'Error deleting' in filepath:
tf1 = out.find('exported successfully to: ')
tmpfilename = out[tf1 + len('exported successfully to: '):].strip()
error_remove = True
else:
tmpfilename = re.sub('Archive exported successfully to: ', '', out.rstrip())
if mylar.CONFIG.FILE_OPTS == 'move':
tmpfilename = re.sub('\(Original deleted\)', '', tmpfilename).strip()
tmpf = tmpfilename.decode('utf-8')
filepath = os.path.join(comicpath, tmpf)
if filename.lower() != tmpf.lower() and tmpf.endswith('(1).cbz'):
logger.fdebug('New filename [%s] is named incorrectly due to duplication during metatagging - Making sure it\'s named correctly [%s].' % (tmpf, filename))
tmpfilename = filename
filepath_new = os.path.join(comicpath, tmpfilename)
try:
os.rename(filepath, filepath_new)
filepath = filepath_new
except:
logger.warn('%s unable to rename file to accomodate metatagging cbz to the same filename' % module)
if not os.path.isfile(filepath):
logger.fdebug(module + 'Trying utf-8 conversion.')
tmpf = tmpfilename.encode('utf-8')
filepath = os.path.join(comicpath, tmpf)
if not os.path.isfile(filepath):
logger.fdebug(module + 'Trying latin-1 conversion.')
tmpf = tmpfilename.encode('Latin-1')
filepath = os.path.join(comicpath, tmpf)
logger.fdebug(module + '[COMIC-TAGGER][CBR-TO-CBZ] New filename: ' + filepath)
initial_ctrun = False
elif initial_ctrun and 'Archive is not a RAR' in out:
logger.fdebug('%s Output: %s' % (module,out))
logger.warn(module + '[COMIC-TAGGER] file is not in a RAR format: ' + filename)
initial_ctrun = False
elif initial_ctrun:
initial_ctrun = False
if 'file is not expected size' in out:
logger.fdebug('%s Output: %s' % (module,out))
tidyup(og_filepath, new_filepath, new_folder, manualmeta)
return 'corrupt'
else:
logger.warn(module + '[COMIC-TAGGER][CBR-TO-CBZ] Failed to convert cbr to cbz - check permissions on folder : ' + mylar.CONFIG.CACHE_DIR + ' and/or the location where Mylar is trying to tag the files from.')
tidyup(og_filepath, new_filepath, new_folder, manualmeta)
return 'fail'
elif 'Cannot find' in out:
logger.fdebug('%s Output: %s' % (module,out))
logger.warn(module + '[COMIC-TAGGER] Unable to locate file: ' + filename)
file_error = 'file not found||' + filename
return file_error
elif 'not a comic archive!' in out:
logger.fdebug('%s Output: %s' % (module,out))
logger.warn(module + '[COMIC-TAGGER] Unable to locate file: ' + filename)
file_error = 'file not found||' + filename
return file_error
else:
logger.info(module + '[COMIC-TAGGER] Successfully wrote ' + tagdisp + ' [' + filepath + ']')
i+=1
except OSError, e:
logger.warn(module + '[COMIC-TAGGER] Unable to run comictagger with the options provided: ' + re.sub(f_tagoptions[f_tagoptions.index(mylar.CONFIG.COMICVINE_API)], 'REDACTED', str(script_cmd)))
tidyup(filepath, new_filepath, new_folder, manualmeta)
return "fail"
if mylar.CONFIG.CBR2CBZ_ONLY and initial_ctrun == False:
break
return filepath
def tidyup(filepath, new_filepath, new_folder, manualmeta):
if all([new_filepath is not None, new_folder is not None]):
if mylar.CONFIG.FILE_OPTS == 'copy' and manualmeta == False:
if all([os.path.exists(new_folder), os.path.isfile(filepath)]):
shutil.rmtree(new_folder)
elif os.path.exists(new_filepath) and not os.path.exists(filepath):
shutil.move(new_filepath, filepath + '.BAD')
else:
if os.path.exists(new_filepath) and not os.path.exists(filepath):
shutil.move(new_filepath, filepath + '.BAD')
if all([os.path.exists(new_folder), os.path.isfile(filepath)]):
shutil.rmtree(new_folder)
| 13,638 | Python | .py | 248 | 43.887097 | 227 | 0.613522 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,222 | weeklypull.py | evilhero_mylar/mylar/weeklypull.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import sys
import fileinput
import csv
import getopt
import sqlite3
import urllib
import os
import time
import re
import datetime
import shutil
import mylar
from mylar import db, updater, helpers, logger, newpull, importer, mb, locg
def pullit(forcecheck=None, weeknumber=None, year=None):
myDB = db.DBConnection()
if weeknumber is None:
popit = myDB.select("SELECT count(*) FROM sqlite_master WHERE name='weekly' and type='table'")
if popit:
try:
pull_date = myDB.selectone("SELECT SHIPDATE from weekly").fetchone()
logger.info(u"Weekly pull list present - checking if it's up-to-date..")
if (pull_date is None):
pulldate = '00000000'
else:
pulldate = pull_date['SHIPDATE']
except (sqlite3.OperationalError, TypeError), msg:
logger.info(u"Error Retrieving weekly pull list - attempting to adjust")
myDB.action("DROP TABLE weekly")
myDB.action("CREATE TABLE IF NOT EXISTS weekly (SHIPDATE TEXT, PUBLISHER TEXT, ISSUE TEXT, COMIC VARCHAR(150), EXTRA TEXT, STATUS TEXT, ComicID TEXT, IssueID TEXT, CV_Last_Update TEXT, DynamicName TEXT, weeknumber TEXT, year TEXT, volume TEXT, seriesyear TEXT, annuallink TEXT, format TEXT, rowid INTEGER PRIMARY KEY)")
pulldate = '00000000'
logger.fdebug(u"Table re-created, trying to populate")
else:
logger.info(u"No pullist found...I'm going to try and get a new list now.")
pulldate = '00000000'
else:
pulldate = None
if pulldate is None and weeknumber is None:
pulldate = '00000000'
#only for pw-file or ALT_PULL = 1
newrl = os.path.join(mylar.CONFIG.CACHE_DIR, 'newreleases.txt')
mylar.PULLBYFILE = False
if mylar.CONFIG.ALT_PULL == 1:
#logger.info('[PULL-LIST] The Alt-Pull method is currently broken. Defaulting back to the normal method of grabbing the pull-list.')
logger.info('[PULL-LIST] Populating & Loading pull-list data directly from webpage')
newpull.newpull()
elif mylar.CONFIG.ALT_PULL == 2:
logger.info('[PULL-LIST] Populating & Loading pull-list data directly from alternate website')
if pulldate is not None:
chk_locg = locg.locg('00000000') #setting this to 00000000 will do a Recreate on every call instead of a Refresh
else:
logger.info('[PULL-LIST] Populating & Loading pull-list data directly from alternate website for specific week of %s, %s' % (weeknumber, year))
chk_locg = locg.locg(weeknumber=weeknumber, year=year)
if chk_locg['status'] == 'up2date':
logger.info('[PULL-LIST] Pull-list is already up-to-date with ' + str(chk_locg['count']) + 'issues. Polling watchlist against it to see if anything is new.')
mylar.PULLNEW = 'no'
return new_pullcheck(chk_locg['weeknumber'],chk_locg['year'])
elif chk_locg['status'] == 'success':
logger.info('[PULL-LIST] Weekly Pull List successfully loaded with ' + str(chk_locg['count']) + ' issues.')
return new_pullcheck(chk_locg['weeknumber'],chk_locg['year'])
elif chk_locg['status'] == 'update_required':
logger.warn('[PULL-LIST] Your version of Mylar is not up-to-date. You MUST update before this works')
return
else:
logger.info('[PULL-LIST] Unable to retrieve weekly pull-list. Dropping down to legacy method of PW-file')
mylar.PULLBYFILE = pull_the_file(newrl)
else:
logger.info('[PULL-LIST] Populating & Loading pull-list data from file')
mylar.PULLBYFILE = pull_the_file(newrl)
#set newrl to a manual file to pull in against that particular file
#newrl = '/mylar/tmp/newreleases.txt'
#newtxtfile header info ("SHIPDATE\tPUBLISHER\tISSUE\tCOMIC\tEXTRA\tSTATUS\n")
#STATUS denotes default status to be applied to pulllist in Mylar (default = Skipped)
if mylar.CONFIG.ALT_PULL != 2 or mylar.PULLBYFILE is True:
newfl = os.path.join(mylar.CONFIG.CACHE_DIR, 'Clean-newreleases.txt')
newtxtfile = open(newfl, 'wb')
if check(newrl, 'Service Unavailable'):
logger.info('Retrieval site is offline at the moment.Aborting pull-list update amd will try again later.')
pullitcheck(forcecheck=forcecheck)
else:
pass
#Prepare the Substitute name switch for pulllist to comic vine conversion
substitutes = os.path.join(mylar.DATA_DIR, "substitutes.csv")
if not os.path.exists(substitutes):
logger.debug('no substitues.csv file located - not performing substitutions on weekly pull list')
substitute_check = False
else:
substitute_check = True
#shortrep is the name to be replaced, longrep the replacement
shortrep=[]
longrep=[]
#open the file data
with open(substitutes) as f:
reader = csv.reader(f, delimiter='|')
for row in reader:
if not row[0].startswith('#'):
logger.fdebug("Substitutes file read : " +str(row))
shortrep.append(row[0])
longrep.append(row[1])
f.close()
not_these=['PREVIEWS',
'Shipping',
'Every Wednesday',
'Please check with',
'PREMIER PUBLISHERS',
'BOOKS',
'COLLECTIBLES',
'MCFARLANE TOYS',
'New Releases',
'Upcoming Releases']
excludes=['2ND PTG',
'3RD PTG',
'4TH PTG',
'5TH PTG',
'6TH PTG',
'7TH PTG',
'8TH PTG',
'9TH PTG',
'NEW PTG',
'POSTER',
'COMBO PACK']
# this checks for the following lists
# first need to only look for checkit variables
checkit=['COMICS',
'IDW PUBLISHING',
'MAGAZINES',
'MERCHANDISE']
#'COMIC & GRAPHIC NOVELS',
#if COMICS is found, determine which publisher
checkit2=['DC',
'MARVEL',
'DARK HORSE',
'IMAGE']
# used to determine type of comic (one shot, hardcover, tradeback, softcover, graphic novel)
cmty=['HC',
'TP',
'GN',
'SC',
'ONE SHOT',
'PI']
#denotes issues that contain special characters within that would normally fail when checked if issue ONLY contained numerics.
#add freely, just lowercase and exclude decimals (they get stripped during comparisons)
specialissues = {'au', 'ai', 'inh', 'now', 'mu'}
pub = "COMICS"
prevcomic = ""
previssue = ""
for i in open(newrl):
if not i.strip():
continue
if 'MAGAZINES' in i: break
if 'MERCHANDISE' in i: break
for nono in not_these:
if nono in i:
#let's try and grab the date for future pull checks
if i.startswith('Shipping') or i.startswith('New Releases') or i.startswith('Upcoming Releases'):
shipdatechk = i.split()
if i.startswith('Shipping'):
shipdate = shipdatechk[1]
elif i.startswith('New Releases'):
shipdate = shipdatechk[3]
elif i.startswith('Upcoming Releases'):
shipdate = shipdatechk[3]
sdsplit = shipdate.split('/')
mo = sdsplit[0]
dy = sdsplit[1]
if len(mo) == 1: mo = "0" + sdsplit[0]
if len(dy) == 1: dy = "0" + sdsplit[1]
shipdate = sdsplit[2] + "-" + mo + "-" + dy
shipdaterep = shipdate.replace('-', '')
pulldate = re.sub('-', '', str(pulldate))
logger.fdebug("shipdate: " + str(shipdaterep))
logger.fdebug("today: " + str(pulldate))
if pulldate == shipdaterep:
logger.info(u"No new pull-list available - will re-check again in 24 hours.")
mylar.PULLNEW = 'no'
return pullitcheck()
else:
logger.info(u"Preparing to update to the new listing.")
break
else:
mylar.PULLNEW = 'yes'
for yesyes in checkit:
if yesyes in i:
#logger.info('yesyes found: ' + yesyes)
if format(str(yesyes)) == 'COMICS':
#logger.info('yesyes = comics: ' + format(str(yesyes)))
for chkchk in checkit2:
flagged = "no"
#logger.info('chkchk is : ' + chkchk)
if chkchk in i:
#logger.info('chkchk found in i: ' + chkchk)
bl = i.split()
blchk = str(bl[0]) + " " + str(bl[1])
if chkchk in blchk:
pub = format(str(chkchk)) + " COMICS"
#logger.info("chkchk: " + str(pub))
break
else:
#logger.info('chkchk not in i - i.findcomics: ' + str(i.find("COMICS")) + ' length: ' + str(len(i.strip())))
if all([i.find("COMICS") < 1, len(i.strip()) == 6]) or ("GRAPHIC NOVELS" in i):
# if i.find("COMICS") < 1 and (len(i.strip()) == 6 or "& GRAPHIC NOVELS" in i):
pub = "COMICS"
#logger.info("i.find comics & len =6 : " + pub)
break
elif i.find("COMICS") > 12:
#logger.info("comics word found in comic title")
flagged = "yes"
break
else:
#logger.info('yesyes not found: ' + yesyes + ' i.findcomics: ' + str(i.find("COMICS")) + ' length: ' + str(len(i.strip())))
if all([i.find("COMICS") < 1, len(i.strip()) == 6]) or ("GRAPHIC NOVELS" in i):
#logger.info("format string not comics & i.find < 1: " + pub)
pub = "COMICS"
break
else:
pub = format(str(yesyes))
#logger.info("format string not comics & i.find > 1: " + pub)
break
if flagged == "no":
break
else:
dupefound = "no"
if '#' in i:
issname = i.split()
#print (issname)
issnamec = len(issname)
n = 0
while (n < issnamec):
#find the issue
if '#' in (issname[n]):
if issname[n] == "PI":
issue = "NA"
break
#this is to ensure we don't get any comps added by removing them entirely (ie. #1-4, etc)
x = None
try:
x = float(re.sub('#', '', issname[n].strip()))
except ValueError, e:
if any(d in re.sub(r'[^a-zA-Z0-9]', '', issname[n]).strip() for d in specialissues):
issue = issname[n]
else:
logger.fdebug('Comp issue set detected as : ' + str(issname[n]) + '. Ignoring.')
issue = 'NA'
else:
issue = issname[n]
if 'ongoing' not in issname[n -1].lower() and '(vu)' not in issname[n -1].lower():
#print ("issue found : " + issname[n])
comicend = n - 1
else:
comicend = n - 2
break
n+=1
if issue == "": issue = 'NA'
#find comicname
comicnm = issname[1]
n = 2
while (n < comicend + 1):
comicnm = comicnm + " " + issname[n]
n+=1
comcnm = re.sub('1 FOR \$1', '', comicnm).strip()
#logger.info("Comicname: " + str(comicnm) )
#get remainder
try:
comicrm = issname[comicend +2]
except:
try:
comicrm = issname[comicend +1]
except:
try:
comicrm = issname[comicend]
except:
comicrm = '$'
if '$' in comicrm:
comicrm="None"
n = (comicend + 3)
while (n < issnamec):
if '$' in (issname[n]):
break
comicrm = str(comicrm) + " " + str(issname[n])
n+=1
#logger.info("Comic Extra info: " + str(comicrm) )
#logger.info("ship: " + str(shipdate))
#logger.info("pub: " + str(pub))
#logger.info("issue: " + str(issue))
#--let's make sure we don't wipe out decimal issues ;)
# if '.' in issue:
# issue_decimal = re.compile(r'[^\d.]+')
# issue = issue_decimal.sub('', str(issue))
# else: issue = re.sub('#','', issue)
issue = re.sub('#', '', issue)
#issue = re.sub("\D", "", str(issue))
#store the previous comic/issue for comparison to filter out duplicate issues/alt covers
#print ("Previous Comic & Issue: " + str(prevcomic) + "--" + str(previssue))
dupefound = "no"
else:
#if it doesn't have a '#' in the line, then we know it's either
#a special edition of some kind, or a non-comic
issname = i.split()
#print (issname)
issnamec = len(issname)
n = 1
issue = ''
while (n < issnamec):
#find the type of non-issue (TP,HC,GN,SC,OS,PI etc)
for cm in cmty:
if "ONE" in issue and "SHOT" in issname[n +1]: issue = "OS"
if cm == (issname[n]):
if issname[n] == 'PI':
issue = 'NA'
break
issue = issname[n]
#print ("non-issue found : " + issue)
comicend = n - 1
break
n+=1
#if the comic doesn't have an issue # or a keyword, adjust.
#set it to 'NA' and it'll be filtered out anyways.
if issue == "" or issue is None:
issue = 'NA'
comicend = n - 1 #comicend = comicend - 1 (adjustment for nil)
#find comicname
comicnm = issname[1]
n = 2
while (n < comicend + 1):
#stupid - this errors out if the array mistakingly goes to far.
try:
comicnm = comicnm + " " + issname[n]
except IndexError:
#print ("went too far looking at this comic...adjusting.")
comicnm = comicnm
break
n+=1
#print ("Comicname: " + str(comicnm) )
#get remainder
if len(issname) <= (comicend + 2):
comicrm = "None"
else:
#print ("length:" + str(len(issname)))
#print ("end:" + str(comicend + 2))
comicrm = issname[comicend +2]
if '$' in comicrm:
comicrm="None"
n = (comicend + 3)
while (n < issnamec):
if '$' in (issname[n]) or 'PI' in (issname[n]):
break
comicrm = str(comicrm) + " " + str(issname[n])
n+=1
#print ("Comic Extra info: " + str(comicrm) )
if "NA" not in issue and issue != "":
#print ("shipdate:" + str(shipdate))
#print ("pub: " + str(pub))
#print ("issue: " + str(issue))
dupefound = "no"
#-- remove html tags when alt_pull is enabled
if mylar.CONFIG.ALT_PULL == 1:
if '&' in comicnm:
comicnm = re.sub('&', '&', comicnm).strip()
if '&' in pub:
pub = re.sub('&', '&', pub).strip()
if '&' in comicrm:
comicrm = re.sub('&', '&', comicrm).strip()
#--start duplicate comic / issue chk
# pullist has shortforms of a series' title sometimes and causes problems
if 'O/T' in comicnm:
comicnm = re.sub('O/T', 'OF THE', comicnm)
if substitute_check == True:
#Step through the list - storing an index
for repindex, repcheck in enumerate(shortrep):
if len(comicnm) >= len(repcheck):
#if the leftmost chars match the short text then replace them with the long text
if comicnm[:len(repcheck)]==repcheck:
logger.fdebug("Switch worked on " +comicnm + " replacing " + str(repcheck) + " with " + str(longrep[repindex]))
comicnm = re.sub(repcheck, longrep[repindex], comicnm)
for excl in excludes:
if excl in str(comicrm):
#duplicate comic / issue detected - don't add...
dupefound = "yes"
if prevcomic == str(comicnm) and previssue == str(issue):
#duplicate comic/issue detected - don't add...
dupefound = "yes"
#--end duplicate chk
if (dupefound != "yes") and ('NA' not in str(issue)):
newtxtfile.write(str(shipdate) + '\t' + str(pub) + '\t' + str(issue) + '\t' + str(comicnm) + '\t' + str(comicrm) + '\tSkipped' + '\n')
prevcomic = str(comicnm)
previssue = str(issue)
newtxtfile.close()
if all([pulldate == '00000000', mylar.CONFIG.ALT_PULL != 2]) or mylar.PULLBYFILE is True:
pulldate = shipdate
try:
weektmp = datetime.date(*(int(s) for s in pulldate.split('-')))
except TypeError:
weektmp = datetime.date.today()
weeknumber = weektmp.strftime("%U")
logger.info(u"Populating the NEW Weekly Pull list into Mylar for week " + str(weeknumber))
myDB.action("drop table if exists weekly")
myDB.action("CREATE TABLE IF NOT EXISTS weekly (SHIPDATE, PUBLISHER TEXT, ISSUE TEXT, COMIC VARCHAR(150), EXTRA TEXT, STATUS TEXT, ComicID TEXT, IssueID TEXT, CV_Last_Update TEXT, DynamicName TEXT, weeknumber TEXT, year TEXT, volume TEXT, seriesyear TEXT, annuallink TEXT, format TEXT, rowid INTEGER PRIMARY KEY)")
csvfile = open(newfl, "rb")
creader = csv.reader(csvfile, delimiter='\t')
t=1
for row in creader:
if "MERCHANDISE" in row: break
if "MAGAZINES" in row: break
if "BOOK" in row: break
try:
cl_d = mylar.filechecker.FileChecker()
cl_dyninfo = cl_d.dynamic_replace(row[3])
dynamic_name = re.sub('[\|\s]','', cl_dyninfo['mod_seriesname'].lower()).strip()
controlValueDict = {'COMIC': row[3],
'ISSUE': row[2],
'EXTRA': row[4]}
newValueDict = {'SHIPDATE': row[0],
'PUBLISHER': row[1],
'STATUS': row[5],
'COMICID': None,
'DYNAMICNAME': dynamic_name,
'WEEKNUMBER': int(weeknumber),
'YEAR': mylar.CURRENT_YEAR}
myDB.upsert("weekly", newValueDict, controlValueDict)
except Exception, e:
#print ("Error - invald arguments...-skipping")
pass
t+=1
csvfile.close()
#let's delete the files
os.remove(os.path.join(mylar.CONFIG.CACHE_DIR, 'Clean-newreleases.txt'))
os.remove(os.path.join(mylar.CONFIG.CACHE_DIR, 'newreleases.txt'))
logger.info(u"Weekly Pull List successfully loaded.")
if mylar.CONFIG.ALT_PULL != 2 or mylar.PULLBYFILE is True:
pullitcheck(forcecheck=forcecheck)
def pullitcheck(comic1off_name=None, comic1off_id=None, forcecheck=None, futurepull=None, issue=None):
if futurepull is None:
logger.info(u"Checking the Weekly Releases list for comics I'm watching...")
else:
logger.info('Checking the Future Releases list for upcoming comics I am watching for...')
myDB = db.DBConnection()
not_t = ['TP',
'NA',
'HC',
'PI']
not_c = ['PTG',
'COMBO PACK',
'(PP #']
lines = []
unlines = []
llen = []
ccname = []
pubdate = []
latestissue = []
w = 0
wc = 0
tot = 0
chkout = []
watchfnd = []
watchfndiss = []
watchfndextra = []
alternate = []
#print ("----------WATCHLIST--------")
a_list = []
b_list = []
comicid = []
if comic1off_name is None:
#let's read in the comic.watchlist from the db here
#cur.execute("SELECT ComicID, ComicName_Filesafe, ComicYear, ComicPublisher, ComicPublished, LatestDate, ForceContinuing, AlternateSearch, LatestIssue from comics WHERE Status = 'Active'")
weeklylist = []
comiclist = myDB.select("SELECT * FROM comics WHERE Status='Active'")
if comiclist is None:
pass
else:
for weekly in comiclist:
#assign it.
weeklylist.append({"ComicName": weekly['ComicName'],
"ComicID": weekly['ComicID'],
"ComicName_Filesafe": weekly['ComicName_Filesafe'],
"ComicYear": weekly['ComicYear'],
"ComicPublisher": weekly['ComicPublisher'],
"ComicPublished": weekly['ComicPublished'],
"LatestDate": weekly['LatestDate'],
"LatestIssue": weekly['LatestIssue'],
"ForceContinuing": weekly['ForceContinuing'],
"AlternateSearch": weekly['AlternateSearch'],
"DynamicName": weekly['DynamicComicName']})
if len(weeklylist) > 0:
for week in weeklylist:
if 'Present' in week['ComicPublished'] or (helpers.now()[:4] in week['ComicPublished']) or week['ForceContinuing'] == 1:
# this gets buggered up when series are named the same, and one ends in the current
# year, and the new series starts in the same year - ie. Avengers
# lets' grab the latest issue date and see how far it is from current
# anything > 45 days we'll assume it's a false match ;)
logger.fdebug("ComicName: " + week['ComicName'])
latestdate = week['LatestDate']
logger.fdebug("latestdate: " + str(latestdate))
if latestdate[8:] == '':
if '-' in latestdate[:4] and not latestdate.startswith('20'):
#pull-list f'd up the date by putting '15' instead of '2015' causing 500 server errors
st_date = latestdate.find('-')
st_remainder = latestdate[st_date+1:]
st_year = latestdate[:st_date]
year = '20' + st_year
latestdate = str(year) + '-' + str(st_remainder)
#logger.fdebug('year set to: ' + latestdate)
else:
logger.fdebug("invalid date " + str(latestdate) + " appending 01 for day for continuation.")
latest_day = '01'
else:
latest_day = latestdate[8:]
c_date = datetime.date(int(latestdate[:4]), int(latestdate[5:7]), int(latest_day))
n_date = datetime.date.today()
logger.fdebug("c_date : " + str(c_date) + " ... n_date : " + str(n_date))
recentchk = (n_date - c_date).days
logger.fdebug("recentchk: " + str(recentchk) + " days")
chklimit = helpers.checkthepub(week['ComicID'])
logger.fdebug("Check date limit set to : " + str(chklimit))
logger.fdebug(" ----- ")
if recentchk < int(chklimit) or week['ForceContinuing'] == 1:
if week['ForceContinuing'] == 1:
logger.fdebug('Forcing Continuing Series enabled for series...')
# let's not even bother with comics that are not in the Present.
a_list.append(week['ComicName'])
b_list.append(week['ComicYear'])
comicid.append(week['ComicID'])
pubdate.append(week['ComicPublished'])
latestissue.append(week['LatestIssue'])
lines.append(a_list[w].strip())
unlines.append(a_list[w].strip())
w+=1 # we need to increment the count here, so we don't count the same comics twice (albeit with alternate names)
#here we load in the alternate search names for a series and assign them the comicid and
#alternate names
Altload = helpers.LoadAlternateSearchNames(week['AlternateSearch'], week['ComicID'])
if Altload == 'no results':
pass
else:
wc = 0
alt_cid = Altload['ComicID']
n = 0
iscnt = Altload['Count']
while (n <= iscnt):
try:
altval = Altload['AlternateName'][n]
except IndexError:
break
cleanedname = altval['AlternateName']
a_list.append(altval['AlternateName'])
b_list.append(week['ComicYear'])
comicid.append(alt_cid)
pubdate.append(week['ComicPublished'])
latestissue.append(week['LatestIssue'])
lines.append(a_list[w +wc].strip())
unlines.append(a_list[w +wc].strip())
logger.fdebug('loading in Alternate name for ' + str(cleanedname))
n+=1
wc+=1
w+=wc
else:
logger.fdebug("Determined to not be a Continuing series at this time.")
else:
# if it's a one-off check (during an add series), load the comicname here and ignore below.
logger.fdebug("This is a one-off for " + comic1off_name + ' [ latest issue: ' + str(issue) + ' ]')
lines.append(comic1off_name.strip())
unlines.append(comic1off_name.strip())
comicid.append(comic1off_id)
latestissue.append(issue)
w = 1
if w >= 1:
cnt = int(w -1)
cntback = int(w -1)
kp = []
ki = []
kc = []
otot = 0
logger.fdebug("You are watching for: " + str(w) + " comics")
#print ("----------THIS WEEK'S PUBLISHED COMICS------------")
if w > 0:
while (cnt > -1):
latestiss = latestissue[cnt]
if mylar.CONFIG.ALT_PULL != 2:
lines[cnt] = lines[cnt].upper()
#llen[cnt] = str(llen[cnt])
logger.fdebug("looking for : " + lines[cnt])
cl_d = mylar.filechecker.FileChecker()
cl_dyninfo = cl_d.dynamic_replace(lines[cnt])
dynamic_name = re.sub('[\|\s]','', cl_dyninfo['mod_seriesname'].lower()).strip()
sqlsearch = '%' + dynamic_name + '%'
logger.fdebug("searchsql: " + sqlsearch)
if futurepull is None:
weekly = myDB.select('SELECT PUBLISHER, ISSUE, COMIC, EXTRA, SHIPDATE, DynamicName FROM weekly WHERE DynamicName LIKE (?) COLLATE NOCASE', [sqlsearch])
else:
weekly = myDB.select('SELECT PUBLISHER, ISSUE, COMIC, EXTRA, SHIPDATE FROM future WHERE COMIC LIKE (?) COLLATE NOCASE', [sqlsearch])
#cur.execute('SELECT PUBLISHER, ISSUE, COMIC, EXTRA, SHIPDATE FROM weekly WHERE COMIC LIKE (?)', [lines[cnt]])
for week in weekly:
if week == None:
break
for nono in not_t:
if nono in week['PUBLISHER']:
#logger.fdebug("nono present")
continue
if nono in week['ISSUE']:
#logger.fdebug("graphic novel/tradeback detected..ignoring.")
continue
for nothere in not_c:
if week['EXTRA'] is not None:
if nothere in week['EXTRA']:
continue
comicnm = week['COMIC']
dyn_comicnm = week['DynamicName']
dyn_watchnm = dynamic_name
logger.fdebug("comparing" + comicnm + "..to.." + unlines[cnt].upper())
watchcomic = unlines[cnt]
logger.fdebug("watchcomic : " + watchcomic) # / mod :" + str(modwatchcomic))
logger.fdebug("comicnm : " + comicnm) # / mod :" + str(modcomicnm))
if dyn_comicnm == dyn_watchnm:
if mylar.CONFIG.ANNUALS_ON:
if 'annual' in watchcomic.lower() and 'annual' not in comicnm.lower():
logger.fdebug('Annual detected in issue, but annuals are not enabled and no series match in wachlist.')
continue
else:
#(annual in comicnm & in watchcomic) or (annual in comicnm & not in watchcomic)(with annuals on) = match.
pass
else:
#annuals off
if ('annual' in comicnm.lower() and 'annual' not in watchcomic.lower()) or ('annual' in watchcomic.lower() and 'annual' not in comicnm.lower()):
logger.fdebug('Annual detected in issue, but annuals are not enabled and no series match in wachlist.')
continue
else:
#annual in comicnm & in watchcomic (with annuals off) = match.
pass
logger.fdebug("matched on:" + comicnm + "..." + watchcomic.upper())
watchcomic = unlines[cnt]
else:
continue
if ("NA" not in week['ISSUE']) and ("HC" not in week['ISSUE']):
if week['EXTRA'] is not None and any(["COMBO PACK" in week['EXTRA'],"2ND PTG" in week['EXTRA'], "3RD PTG" in week['EXTRA']]):
continue
else:
#this all needs to get redone, so the ability to compare issue dates can be done systematically.
#Everything below should be in it's own function - at least the callable sections - in doing so, we can
#then do comparisons when two titles of the same name exist and are by definition 'current'. Issue date comparisons
#would identify the difference between two #1 titles within the same series year, but have different publishing dates.
#Wolverine (2013) & Wolverine (2014) are good examples of this situation.
#of course initially, the issue data for the newer series wouldn't have any issue data associated with it so it would be
#a null value, but given that the 2013 series (as an example) would be from 2013-05-01, it obviously wouldn't be a match to
#the current date & year (2014). Throwing out that, we could just assume that the 2014 would match the #1.
#get the issue number of the 'weeklypull' series.
#load in the actual series issue number's store-date (not publishing date)
#---use a function to check db, then return the results in a tuple/list to avoid db locks.
#if the store-date is >= weeklypull-list date then continue processing below.
#if the store-date is <= weeklypull-list date then break.
### week['ISSUE'] #issue # from pullist
### week['SHIPDATE'] #weeklypull-list date
### comicid[cnt] #comicid of matched series
## if it's a futurepull, the dates get mixed up when two titles exist of the same name
## ie. Wolverine-2011 & Wolverine-2014
## we need to set the compare date to today's date ( Now() ) in this case.
if futurepull:
usedate = datetime.datetime.now().strftime('%Y%m%d') #convert to yyyymmdd
else:
usedate = re.sub("[^0-9]", "", week['SHIPDATE'])
if 'ANNUAL' in comicnm.upper():
chktype = 'annual'
else:
chktype = 'series'
datevalues = loaditup(watchcomic, comicid[cnt], week['ISSUE'], chktype)
date_downloaded = None
altissuenum = None
if datevalues == 'no results':
#if a series is a .NOW on the pullist, it won't match up against anything (probably) on CV
#let's grab the digit from the .NOW, poll it against CV to see if there's any data
#if there is, check the store date to make sure it's a 'new' release.
#if it is a new release that has the same store date as the .NOW, then we assume
#it's the same, and assign it the AltIssueNumber to do extra searches.
if week['ISSUE'].isdigit() == False and '.' not in week['ISSUE']:
altissuenum = re.sub("[^0-9]", "", week['ISSUE']) # carry this through to get added to db later if matches
logger.fdebug('altissuenum is: ' + str(altissuenum))
altvalues = loaditup(watchcomic, comicid[cnt], altissuenum, chktype)
if altvalues == 'no results':
logger.fdebug('No alternate Issue numbering - something is probably wrong somewhere.')
continue
validcheck = checkthis(altvalues[0]['issuedate'], altvalues[0]['status'], usedate)
if validcheck == False:
if date_downloaded is None:
continue
if chktype == 'series':
latest_int = helpers.issuedigits(latestiss)
weekiss_int = helpers.issuedigits(week['ISSUE'])
logger.fdebug('comparing ' + str(latest_int) + ' to ' + str(weekiss_int))
if (latest_int > weekiss_int) and (latest_int != 0 or weekiss_int != 0):
logger.fdebug(str(week['ISSUE']) + ' should not be the next issue in THIS volume of the series.')
logger.fdebug('it should be either greater than ' + str(latestiss) + ' or an issue #0')
continue
else:
logger.fdebug('issuedate:' + str(datevalues[0]['issuedate']))
logger.fdebug('status:' + str(datevalues[0]['status']))
datestatus = datevalues[0]['status']
validcheck = checkthis(datevalues[0]['issuedate'], datestatus, usedate)
if validcheck == True:
if datestatus != 'Downloaded' and datestatus != 'Archived':
pass
else:
logger.fdebug('Issue #' + str(week['ISSUE']) + ' already downloaded.')
date_downloaded = datestatus
else:
if date_downloaded is None:
continue
otot+=1
dontadd = "no"
if dontadd == "no":
tot+=1
if "ANNUAL" in comicnm.upper():
watchfndextra.append("annual")
ComicName = str(unlines[cnt]) + " Annual"
else:
ComicName = str(unlines[cnt])
watchfndextra.append("none")
watchfnd.append(comicnm)
watchfndiss.append(week['ISSUE'])
ComicID = comicid[cnt]
if not mylar.CONFIG.CV_ONLY:
ComicIssue = str(watchfndiss[tot -1] + ".00")
else:
ComicIssue = str(watchfndiss[tot -1])
ComicDate = str(week['SHIPDATE'])
logger.fdebug("Watchlist hit for : " + ComicName + " ISSUE: " + str(watchfndiss[tot -1]))
# here we add to comics.latest
updater.latest_update(ComicID=ComicID, LatestIssue=ComicIssue, LatestDate=ComicDate)
# here we add to upcoming table...
statusupdate = updater.upcoming_update(ComicID=ComicID, ComicName=ComicName, IssueNumber=ComicIssue, IssueDate=ComicDate, forcecheck=forcecheck)
# here we update status of weekly table...
try:
if statusupdate is not None:
cstatusid = []
cstatus = statusupdate['Status']
cstatusid = {"ComicID": statusupdate['ComicID'],
"IssueID": statusupdate['IssueID']}
else:
cstatus = None
cstatusid = None
except:
cstatusid = None
cstatus = None
if date_downloaded is None:
updater.weekly_update(ComicName=week['COMIC'], IssueNumber=ComicIssue, CStatus=cstatus, CID=cstatusid, weeknumber=mylar.CURRENT_WEEKNUMBER, year=mylar.CURRENT_YEAR, altissuenumber=altissuenum)
else:
updater.weekly_update(ComicName=week['COMIC'], IssueNumber=ComicIssue, CStatus=date_downloaded, CID=cstatusid, weeknumber=mylar.CURRENT_WEEKNUMBER, year=mylar.CURRENT_YEAR, altissuenumber=altissuenum)
break
cnt-=1
logger.fdebug("There are " + str(otot) + " comics this week to get!")
logger.info(u"Finished checking for comics on my watchlist.")
return {'status': 'success'}
def new_pullcheck(weeknumber, pullyear, comic1off_name=None, comic1off_id=None, forcecheck=None, issue=None):
#the new pull method (ALT_PULL=2) already has the comicid & issueid (if available) present in the response that's polled by mylar.
#this should be as simple as checking if the comicid exists on the given watchlist, and if so mark it as Wanted in the Upcoming table
#and then once the issueid is present, put it the Wanted table.
myDB = db.DBConnection()
watchlist = []
weeklylist = []
pullist = helpers.listPull(weeknumber,pullyear)
if comic1off_name:
comiclist = myDB.select("SELECT * FROM comics WHERE Status='Active' AND ComicID=?",[comic1off_id])
else:
comiclist = myDB.select("SELECT * FROM comics WHERE Status='Active'")
if comiclist is None:
pass
else:
for weekly in comiclist:
#assign it.
watchlist.append({"ComicName": weekly['ComicName'],
"ComicID": weekly['ComicID'],
"ComicName_Filesafe": weekly['ComicName_Filesafe'],
"ComicYear": weekly['ComicYear'],
"ComicPublisher": weekly['ComicPublisher'],
"ComicPublished": weekly['ComicPublished'],
"LatestDate": weekly['LatestDate'],
"LatestIssue": weekly['LatestIssue'],
"ForceContinuing": weekly['ForceContinuing'],
"AlternateSearch": weekly['AlternateSearch'],
"DynamicName": weekly['DynamicComicName']})
if len(watchlist) > 0:
for watch in watchlist:
listit = [pls for pls in pullist if str(pls) == str(watch['ComicID'])]
#logger.info('listit: %s' % listit)
if 'Present' in watch['ComicPublished'] or (helpers.now()[:4] in watch['ComicPublished']) or watch['ForceContinuing'] == 1 or len(listit) >0:
# this gets buggered up when series are named the same, and one ends in the current
# year, and the new series starts in the same year - ie. Avengers
# lets' grab the latest issue date and see how far it is from current
# anything > 45 days we'll assume it's a false match ;)
#logger.fdebug('[PRESENT] ComicName: %s [%s]' % (watch['ComicName'], watch['ComicID']))
latestdate = watch['LatestDate']
#logger.fdebug("latestdate: " + str(latestdate))
if latestdate[8:] == '':
if '-' in latestdate[:4] and not latestdate.startswith('20'):
#pull-list f'd up the date by putting '15' instead of '2015' causing 500 server errors
st_date = latestdate.find('-')
st_remainder = latestdate[st_date+1:]
st_year = latestdate[:st_date]
year = '20' + st_year
latestdate = str(year) + '-' + str(st_remainder)
#logger.fdebug('year set to: ' + latestdate)
else:
logger.fdebug("invalid date " + str(latestdate) + " appending 01 for day for continuation.")
latest_day = '01'
else:
latest_day = latestdate[8:]
try:
c_date = datetime.date(int(latestdate[:4]), int(latestdate[5:7]), int(latest_day))
except ValueError:
logger.error('Invalid Latest Date returned for ' + watch['ComicName'] + '. Series needs to be refreshed so that is what I am going to do.')
#refresh series here and then continue.
n_date = datetime.date.today()
#logger.fdebug("c_date : " + str(c_date) + " ... n_date : " + str(n_date))
recentchk = (n_date - c_date).days
#logger.fdebug("recentchk: " + str(recentchk) + " days")
chklimit = helpers.checkthepub(watch['ComicID'])
#logger.fdebug("Check date limit set to : " + str(chklimit))
#logger.fdebug(" ----- ")
if recentchk < int(chklimit) or watch['ForceContinuing'] == 1 or len(listit) > 0:
if watch['ForceContinuing'] == 1:
logger.fdebug('Forcing Continuing Series enabled for %s [%s]' % (watch['ComicName'],watch['ComicID']))
# let's not even bother with comics that are not in the Present.
Altload = helpers.LoadAlternateSearchNames(watch['AlternateSearch'], watch['ComicID'])
if Altload == 'no results' or Altload is None:
altnames = None
else:
altnames = []
for alt in Altload['AlternateName']:
altnames.append(alt['AlternateName'])
#pull in the annual IDs attached to the given series here for pinpoint accuracy.
annualist = myDB.select('SELECT * FROM annuals WHERE ComicID=?', [watch['ComicID']])
annual_ids = []
if annualist is None:
pass
else:
for an in annualist:
#logger.info('annuals for %s: %s' % (an['ReleaseComicName'], an['ReleaseComicID']))
if not any([x for x in annual_ids if x['ComicID'] == an['ReleaseComicID']]):
annual_ids.append({'ComicID': an['ReleaseComicID'],
'ComicName': an['ReleaseComicName']})
weeklylist.append({'ComicName': watch['ComicName'],
'SeriesYear': watch['ComicYear'],
'ComicID': watch['ComicID'],
'Pubdate': watch['ComicPublished'],
'latestIssue': watch['LatestIssue'],
'DynamicName': watch['DynamicName'],
'AnnDynamicName': re.sub('annual', '', watch['DynamicName'].lower()).strip(),
'AlternateNames': altnames,
'AnnualIDs': annual_ids})
else:
#logger.fdebug("Determined to not be a Continuing series at this time.")
pass
if len(weeklylist) >= 1:
kp = []
ki = []
kc = []
otot = 0
if not comic1off_id:
logger.fdebug("[WALKSOFTLY] You are watching for: " + str(len(weeklylist)) + " comics")
weekly = myDB.select('SELECT a.comicid, IFNULL(a.Comic,IFNULL(b.ComicName, c.ComicName)) as ComicName, a.rowid, a.issue, a.issueid, c.ComicPublisher, a.weeknumber, a.shipdate, a.dynamicname, a.annuallink FROM weekly as a INNER JOIN annuals as b INNER JOIN comics as c ON b.releasecomicid = a.comicid OR c.comicid = a.comicid OR c.DynamicComicName = a.dynamicname OR a.annuallink = c.comicid WHERE weeknumber = ? AND year = ? GROUP BY a.dynamicname', [int(weeknumber),pullyear]) #comics INNER JOIN weekly ON comics.DynamicComicName = weekly.dynamicname OR comics.comicid = weekly.comicid INNER JOIN annuals ON annuals.comicid = weekly.comicid WHERE weeknumber = ? GROUP BY weekly.dynamicname', [weeknumber])
if mylar.CONFIG.ANNUALS_ON is True:
#Need to loop over the weekly section and check the name of the title against the ComicName in the annuals table
# this is to pick up new #1 annuals that don't exist in the db yet, and won't until a refresh of the series happens.
pass
for week in weekly:
#logger.fdebug('week: %s [%s]' % (week['ComicName'], week['comicid']))
idmatch = None
annualidmatch = None
namematch = None
if week is None:
break
idmatch = [x for x in weeklylist if week['comicid'] is not None and int(x['ComicID']) == int(week['comicid'])]
if mylar.CONFIG.ANNUALS_ON is True:
annualidmatch = [x for x in weeklylist if week['comicid'] is not None and ([xa for xa in x['AnnualIDs'] if int(xa['ComicID']) == int(week['comicid'])])]
if not annualidmatch:
annualidmatch = [x for x in weeklylist if week['annuallink'] is not None and (int(x['ComicID']) == int(week['annuallink']))]
#The above will auto-match against ComicID if it's populated on the pullsite, otherwise do name-matching.
namematch = [ab for ab in weeklylist if ab['DynamicName'] == week['dynamicname']]
#logger.fdebug('rowid: ' + str(week['rowid']))
#logger.fdebug('idmatch: ' + str(idmatch))
#logger.fdebug('annualidmatch: ' + str(annualidmatch))
#logger.fdebug('namematch: ' + str(namematch))
if any([idmatch,namematch,annualidmatch]):
if idmatch and not annualidmatch:
comicname = idmatch[0]['ComicName'].strip()
latestiss = idmatch[0]['latestIssue'].strip()
comicid = idmatch[0]['ComicID'].strip()
logger.fdebug('[WEEKLY-PULL-ID] Series Match to ID --- ' + comicname + ' [' + comicid + ']')
elif annualidmatch:
try:
if 'annual' in week['ComicName'].lower():
comicname = annualidmatch[0]['AnnualIDs'][0]['ComicName'].strip()
else:
comicname = week['ComicName']
except:
comicname = week['ComicName']
latestiss = annualidmatch[0]['latestIssue'].strip()
if mylar.CONFIG.ANNUALS_ON:
comicid = annualidmatch[0]['ComicID'].strip()
else:
comicid = annualidmatch[0]['AnnualIDs'][0]['ComicID'].strip()
logger.fdebug('[WEEKLY-PULL-ANNUAL] Series Match to ID --- ' + comicname + ' [' + comicid + ']')
else:
#if it's a name metch, it means that CV hasn't been populated yet with the necessary data
#do a quick issue check to see if the next issue number is in sequence and not a #1, or like #900
latestiss = namematch[0]['latestIssue'].strip()
try:
diff = int(week['Issue']) - int(latestiss)
except ValueError as e:
logger.warn('[WEEKLY-PULL] Invalid issue number detected. Skipping this entry for the time being.')
continue
if diff >= 0 and diff < 3:
comicname = namematch[0]['ComicName'].strip()
comicid = namematch[0]['ComicID'].strip()
logger.fdebug('[WEEKLY-PULL-NAME] Series Match to Name --- ' + comicname + ' [' + comicid + ']')
else:
logger.fdebug('[WEEKLY-PULL] Series ID:' + namematch[0]['ComicID'] + ' not a match based on issue number comparison [LatestIssue:' + latestiss + '][MatchIssue:' + week['Issue'] + ']')
continue
date_downloaded = None
todaydate = datetime.datetime.today()
try:
ComicDate = str(week['shipdate'])
except TypeError, e:
ComicDate = todaydate.strftime('%Y-%m-%d')
logger.fdebug('[WEEKLY-PULL] Invalid Cover date. Forcing to weekly pull date of : ' + str(ComicDate))
if week['issueid'] is not None:
logger.fdebug('[WEEKLY-PULL] Issue Match to ID --- ' + comicname + ' #' + str(week['issue']) + '[' + comicid + '/' + week['issueid'] + ']')
issueid = week['issueid']
else:
issueid = None
if 'annual' in comicname.lower():
chktype = 'annual'
else:
chktype = 'series'
datevalues = loaditup(comicname, comicid, week['issue'], chktype)
logger.fdebug('datevalues: ' + str(datevalues))
usedate = re.sub("[^0-9]", "", ComicDate).strip()
if datevalues == 'no results':
if week['issue'].isdigit() == False and '.' not in week['issue']:
altissuenum = re.sub("[^0-9]", "", week['issue']) # carry this through to get added to db later if matches
logger.fdebug('altissuenum is: ' + str(altissuenum))
altvalues = loaditup(comicname, comicid, altissuenum, chktype)
if altvalues == 'no results':
logger.fdebug('No alternate Issue numbering - something is probably wrong somewhere.')
continue
validcheck = checkthis(altvalues[0]['issuedate'], altvalues[0]['status'], usedate)
if validcheck == False:
if date_downloaded is None:
continue
if chktype == 'series':
latest_int = helpers.issuedigits(latestiss)
weekiss_int = helpers.issuedigits(week['issue'])
logger.fdebug('comparing ' + str(latest_int) + ' to ' + str(weekiss_int))
if (latest_int > weekiss_int) and (latest_int != 0 or weekiss_int != 0):
logger.fdebug(str(week['issue']) + ' should not be the next issue in THIS volume of the series.')
logger.fdebug('it should be either greater than ' + x['latestIssue'] + ' or an issue #0')
continue
else:
logger.fdebug('issuedate:' + str(datevalues[0]['issuedate']))
logger.fdebug('status:' + str(datevalues[0]['status']))
datestatus = datevalues[0]['status']
validcheck = checkthis(datevalues[0]['issuedate'], datestatus, usedate)
if validcheck == True:
if datestatus != 'Downloaded' and datestatus != 'Archived':
pass
else:
logger.fdebug('Issue #' + str(week['issue']) + ' already downloaded.')
date_downloaded = datestatus
else:
if date_downloaded is None:
continue
logger.fdebug("Watchlist hit for : " + week['ComicName'] + " #: " + str(week['issue']))
if mylar.CURRENT_WEEKNUMBER is None:
mylar.CURRENT_WEEKNUMBER = todaydate.strftime("%U")
# if int(mylar.CURRENT_WEEKNUMBER) == int(weeknumber):
# here we add to comics.latest
updater.latest_update(ComicID=comicid, LatestIssue=week['issue'], LatestDate=ComicDate)
# here we add to upcoming table...
statusupdate = updater.upcoming_update(ComicID=comicid, ComicName=comicname, IssueNumber=week['issue'], IssueDate=ComicDate, forcecheck=forcecheck, weekinfo={'weeknumber':weeknumber,'year':pullyear})
logger.fdebug('statusupdate: ' + str(statusupdate))
# here we update status of weekly table...
try:
if statusupdate is not None:
cstatusid = []
cstatus = statusupdate['Status']
cstatusid = {"ComicID": statusupdate['ComicID'],
"IssueID": statusupdate['IssueID']}
else:
cstatus = None
cstatusid = None
except:
cstatusid = None
cstatus = None
logger.fdebug('date_downloaded: ' + str(date_downloaded))
controlValue = {"rowid": int(week['rowid'])}
if any([(idmatch and not namematch),(idmatch and annualidmatch and namematch),(annualidmatch and not namematch),(annualidmatch or idmatch and not namematch)]):
if annualidmatch:
newValue = {"ComicID": annualidmatch[0]['ComicID']}
else:
#if it matches to id, but not name - consider this an alternate and use the cv name and update based on ID so we don't get duplicates
newValue = {"ComicID": cstatusid['ComicID']}
newValue['COMIC'] = comicname
newValue['ISSUE'] = week['issue']
newValue['WEEKNUMBER'] = int(weeknumber)
newValue['YEAR'] = pullyear
if issueid:
newValue['IssueID'] = issueid
else:
newValue = {"ComicID": comicid,
"COMIC": week['ComicName'],
"ISSUE": week['issue'],
"WEEKNUMBER": int(weeknumber),
"YEAR": pullyear}
#logger.fdebug('controlValue:' + str(controlValue))
if not issueid:
try:
if cstatusid['IssueID']:
newValue['IssueID'] = cstatusid['IssueID']
else:
cidissueid = None
except:
cidissueid = None
#logger.fdebug('cstatus:' + str(cstatus))
if any([date_downloaded, cstatus]):
if date_downloaded:
cst = date_downloaded
else:
cst = cstatus
newValue['Status'] = cst
else:
if mylar.CONFIG.AUTOWANT_UPCOMING:
newValue['Status'] = 'Wanted'
else:
newValue['Status'] = 'Skipped'
#setting this here regardless, as it will be a match for a watchlist hit at this point anyways - so link it here what's availalbe.
#logger.fdebug('newValue:' + str(newValue))
myDB.upsert("weekly", newValue, controlValue)
#if the issueid exists on the pull, but not in the series issue list, we need to forcibly refresh the series so it's in line
if issueid:
#logger.info('issue id check passed.')
if annualidmatch:
isschk = myDB.selectone('SELECT * FROM annuals where IssueID=?', [issueid]).fetchone()
else:
isschk = myDB.selectone('SELECT * FROM issues where IssueID=?', [issueid]).fetchone()
if isschk is None:
isschk = myDB.selectone('SELECT * FROM annuals where IssueID=?', [issueid]).fetchone()
if isschk is None:
logger.fdebug('[WEEKLY-PULL] Forcing a refresh of the series to ensure it is current [' + str(comicid) +'].')
anncid = None
seriesyear = None
try:
if all([mylar.CONFIG.ANNUALS_ON is True, len(annualidmatch[0]['AnnualIDs']) == 0]) or all([mylar.CONFIG.ANNUALS_ON is True, annualidmatch[0]['AnnualIDs'][0]['ComicID'] != week['comicid']]):
#if the annual/special on the weekly is not a part of the series, pass in the anncomicid so that it can get added.
anncid = week['comicid']
seriesyear = annualidmatch[0]['SeriesYear']
except Exception as e:
pass
#refresh series.
if anncid is None:
cchk = mylar.importer.updateissuedata(comicid, comicname, calledfrom='weeklycheck')
else:
cchk = mylar.importer.manualAnnual(anncid, comicname, seriesyear, comicid)
else:
logger.fdebug('annual issue exists in db already: ' + str(issueid))
pass
else:
logger.fdebug('issue exists in db already: ' + str(issueid))
if isschk['Status'] == newValue['Status']:
pass
else:
if all([isschk['Status'] != 'Downloaded', isschk['Status'] != 'Snatched', isschk['Status'] != 'Archived', isschk['Status'] != 'Ignored']) and newValue['Status'] == 'Wanted':
#make sure the status is Wanted and that the issue status is identical if not.
newStat = {'Status': 'Wanted'}
ctrlStat = {'IssueID': issueid}
if all([annualidmatch, mylar.CONFIG.ANNUALS_ON]):
myDB.upsert("annuals", newStat, ctrlStat)
else:
myDB.upsert("issues", newStat, ctrlStat)
else:
continue
# else:
# #if it's polling against a future week, don't update anything but the This Week table.
# updater.weekly_update(ComicName=comicname, IssueNumber=week['issue'], CStatus='Wanted', CID=comicid, weeknumber=weeknumber, year=pullyear, altissuenumber=None)
def check(fname, txt):
try:
with open(fname) as dataf:
return any(txt in line for line in dataf)
except:
return None
def loaditup(comicname, comicid, issue, chktype):
myDB = db.DBConnection()
issue_number = helpers.issuedigits(issue)
if chktype == 'annual':
typedisplay = 'annual issue'
logger.fdebug('[' + comicname + '] trying to locate ' + str(typedisplay) + ' ' + str(issue) + ' to do comparitive issue analysis for pull-list')
issueload = myDB.selectone('SELECT * FROM annuals WHERE ComicID=? AND Int_IssueNumber=?', [comicid, issue_number]).fetchone()
else:
typedisplay = 'issue'
logger.fdebug('[' + comicname + '] trying to locate ' + str(typedisplay) + ' ' + str(issue) + ' to do comparitive issue analysis for pull-list')
issueload = myDB.selectone('SELECT * FROM issues WHERE ComicID=? AND Int_IssueNumber=?', [comicid, issue_number]).fetchone()
if issueload is None:
logger.fdebug('No results matched for Issue number - either this is a NEW issue with no data yet, or something is wrong')
return 'no results'
dataissue = []
releasedate = issueload['ReleaseDate']
storedate = issueload['IssueDate']
status = issueload['Status']
if releasedate == '0000-00-00':
logger.fdebug('Store date of 0000-00-00 returned for ' + str(typedisplay) + ' # ' + str(issue) + '. Refreshing series to see if valid date present')
#mismatch = 'no'
#issuerecheck = mylar.importer.addComictoDB(comicid,mismatch,calledfrom='weekly',issuechk=issue_number,issuetype=chktype)
#issuerecheck = mylar.importer.updateissuedata(comicid, comicname, calledfrom='weekly', issuechk=issue_number, issuetype=chktype)
#if issuerecheck is not None:
# for il in issuerecheck:
# #this is only one record..
# releasedate = il['IssueDate']
# storedate = il['ReleaseDate']
# #status = il['Status']
# logger.fdebug('issue-recheck releasedate is : ' + str(releasedate))
# logger.fdebug('issue-recheck storedate of : ' + str(storedate))
if releasedate is not None and releasedate != "None" and releasedate != "":
logger.fdebug('Returning Release Date for ' + str(typedisplay) + ' # ' + str(issue) + ' of ' + str(releasedate))
thedate = re.sub("[^0-9]", "", releasedate) #convert date to numerics only (should be in yyyymmdd)
#return releasedate
else:
logger.fdebug('Returning Publication Date for issue ' + str(typedisplay) + ' # ' + str(issue) + ' of ' + str(storedate))
if storedate is None and storedate != "None" and storedate != "":
logger.fdebug('no issue data available - both release date & store date. Returning no results')
return 'no results'
thedate = re.sub("[^0-9]", "", storedate) #convert date to numerics only (should be in yyyymmdd)
#return storedate
dataissue.append({"issuedate": thedate,
"status": status})
return dataissue
def checkthis(datecheck, datestatus, usedate):
logger.fdebug('Now checking date comparison using an issue store date of ' + str(datecheck))
logger.fdebug('Using a compare date (usedate) of ' + str(usedate))
logger.fdebug('Status of ' + str(datestatus))
#give an allowance of 10 days to datecheck for late publishs (+1.5 weeks)
if int(datecheck) + 10 >= int(usedate):
logger.fdebug('Store Date falls within acceptable range - series MATCH')
valid_check = True
elif int(datecheck) < int(usedate):
if datecheck == '00000000':
logger.fdebug('Issue date retrieved as : ' + str(datecheck) + '. This is unpopulated data on CV, which normally means it\'s a new issue and is awaiting data population.')
valid_check = True
else:
logger.fdebug('The issue date of issue was on ' + str(datecheck) + ' which is prior to ' + str(usedate))
valid_check = False
return valid_check
def pull_the_file(newrl):
import requests
PULLURL = 'https://www.previewsworld.com/shipping/newreleases.txt'
PULL_AGENT = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'}
try:
r = requests.get(PULLURL, verify=True, headers=PULL_AGENT, stream=True)
except requests.exceptions.RequestException as e:
logger.warn(e)
return False
with open(newrl, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
return True
def weekly_check(comicid, issuenum, file=None, path=None, module=None, issueid=None):
if module is None:
module = ''
module += '[WEEKLY-PULL]'
myDB = db.DBConnection()
if issueid is None:
chkit = myDB.selectone('SELECT * FROM weekly WHERE ComicID=? AND ISSUE=?', [comicid, issuenum]).fetchone()
else:
chkit = myDB.selectone('SELECT * FROM weekly WHERE ComicID=? AND IssueID=?', [comicid, issueid]).fetchone()
if chkit is None:
logger.fdebug(module + ' ' + file + ' is not on the weekly pull-list or it is a one-off download that is not supported as of yet.')
return
logger.info(module + ' Issue found on weekly pull-list.')
weekinfo = helpers.weekly_info(chkit['weeknumber'],chkit['year'])
if mylar.CONFIG.WEEKFOLDER:
weekly_singlecopy(comicid, issuenum, file, path, weekinfo)
if mylar.CONFIG.SEND2READ:
send2read(comicid, issueid, issuenum)
return
def weekly_singlecopy(comicid, issuenum, file, path, weekinfo):
module = '[WEEKLY-PULL COPY]'
if mylar.CONFIG.WEEKFOLDER:
desdir = weekinfo['week_folder']
dircheck = mylar.filechecker.validateAndCreateDirectory(desdir, True, module=module)
if dircheck:
pass
else:
desdir = mylar.CONFIG.DESTINATION_DIR
else:
desdir = mylar.CONFIG.GRABBAG_DIR
desfile = os.path.join(desdir, file)
srcfile = os.path.join(path)
try:
shutil.copy2(srcfile, desfile)
except IOError as e:
logger.error(module + ' Could not copy ' + str(srcfile) + ' to ' + str(desfile))
return
logger.info(module + ' Sucessfully copied to ' + desfile.encode('utf-8').strip())
return
def send2read(comicid, issueid, issuenum):
module = '[READLIST]'
if mylar.CONFIG.SEND2READ:
logger.info(module + " Send to Reading List enabled for new pulls. Adding to your readlist in the status of 'Added'")
if issueid is None:
chkthis = myDB.selectone('SELECT * FROM issues WHERE ComicID=? AND Int_IssueNumber=?', [comicid, helpers.issuedigits(issuenum)]).fetchone()
annchk = myDB.selectone('SELECT * FROM annuals WHERE ComicID=? AND Int_IssueNumber=?', [comicid, helpers.issuedigits(issuenum)]).fetchone()
if chkthis is None and annchk is None:
logger.warn(module + ' Unable to locate issue within your series watchlist.')
return
if chkthis is None:
issueid = annchk['IssueID']
elif annchk is None:
issueid = chkthis['IssueID']
else:
#if issue number exists in issues and annuals for given series, break down by year.
#get pulldate.
pullcomp = pulldate[:4]
isscomp = chkthis['ReleaseDate'][:4]
anncomp = annchk['ReleaseDate'][:4]
logger.info(module + ' Comparing :' + str(pullcomp) + ' to issdate: ' + str(isscomp) + ' to annyear: ' + str(anncomp))
if int(pullcomp) == int(isscomp) and int(pullcomp) != int(anncomp):
issueid = chkthis['IssueID']
elif int(pullcomp) == int(anncomp) and int(pullcomp) != int(isscomp):
issueid = annchk['IssueID']
else:
if 'annual' in file.lower():
issueid = annchk['IssueID']
else:
logger.info(module + ' Unsure as to the exact issue this is. Not adding to the Reading list at this time.')
return
read = mylar.readinglist.Readinglist(IssueID=issueid)
read.addtoreadlist()
return
def future_check():
# this is the function that will check the futureupcoming table
# for series that have yet to be released and have no CV data associated with it
# ie. #1 issues would fall into this as there is no series data to poll against until it's released.
# Mylar will look for #1 issues, and in finding any will do the following:
# - check comicvine to see if the series data has been released and / or issue data
# - will automatically import the series (Add A Series) upon finding match
# - will then proceed to mark the issue as Wanted, then remove from the futureupcoming table
# - will then attempt to download the issue(s) in question.
# future to-do
# specify whether you want to 'add a series (Watch For)' or 'mark an issue as a one-off download'.
# currently the 'add series' option in the futurepulllist will attempt to add a series as per normal.
myDB = db.DBConnection()
chkfuture = myDB.select("SELECT * FROM futureupcoming WHERE IssueNumber='1' OR IssueNumber='0'") #is not NULL")
if chkfuture is None:
logger.info("There are not any series on your future-list that I consider to be a NEW series")
else:
cflist = []
#load in the values on an entry-by-entry basis into a tuple, so that we can query the sql clean again.
for cf in chkfuture:
cflist.append({"ComicName": cf['ComicName'],
"IssueDate": cf['IssueDate'],
"IssueNumber": cf['IssueNumber'], #this should be all #1's as the sql above limits the hits.
"Publisher": cf['Publisher'],
"Status": cf['Status']})
logger.fdebug('cflist: ' + str(cflist))
#now we load in
if len(cflist) == 0:
logger.info('No series have been marked as being on auto-watch.')
else:
logger.info('I will be looking to see if any information has been released for ' + str(len(cflist)) + ' series that are NEW series')
#limit the search to just the 'current year' since if it's anything but a #1, it should have associated data already.
#limittheyear = []
#limittheyear.append(cf['IssueDate'][-4:])
search_results = []
for ser in cflist:
matched = False
theissdate = ser['IssueDate'][-4:]
if not theissdate.startswith('20'):
theissdate = ser['IssueDate'][:4]
logger.info('looking for new data for ' + ser['ComicName'] + '[#' + str(ser['IssueNumber']) + '] (' + str(theissdate) + ')')
searchresults = mb.findComic(ser['ComicName'], mode='pullseries', issue=ser['IssueNumber'], limityear=theissdate)
if len(searchresults) > 0:
if len(searchresults) > 1:
logger.info('More than one result returned - this may have to be a manual add, but I\'m going to try to figure it out myself first.')
matches = []
logger.fdebug('Publisher of series to be added: ' + str(ser['Publisher']))
for sr in searchresults:
logger.fdebug('Comparing ' + sr['name'] + ' - to - ' + ser['ComicName'])
tmpsername = re.sub('[\'\*\^\%\$\#\@\!\/\,\.\:\(\)]', '', ser['ComicName']).strip()
tmpsrname = re.sub('[\'\*\^\%\$\#\@\!\/\,\.\:\(\)]', '', sr['name']).strip()
tmpsername = re.sub('\-', '', tmpsername)
if tmpsername.lower().startswith('the '):
tmpsername = re.sub('the ', '', tmpsername.lower()).strip()
else:
tmpsername = re.sub(' the ', '', tmpsername.lower()).strip()
tmpsrname = re.sub('\-', '', tmpsrname)
if tmpsrname.lower().startswith('the '):
tmpsrname = re.sub('the ', '', tmpsrname.lower()).strip()
else:
tmpsrname = re.sub(' the ', '', tmpsrname.lower()).strip()
tmpsername = re.sub(' and ', '', tmpsername.lower()).strip()
tmpsername = re.sub(' & ', '', tmpsername.lower()).strip()
tmpsrname = re.sub(' and ', '', tmpsrname.lower()).strip()
tmpsrname = re.sub(' & ', '', tmpsrname.lower()).strip()
#append the cleaned-up name to get searched later against if necessary.
search_results.append({'name': tmpsrname,
'comicid': sr['comicid']})
tmpsername = re.sub('\s', '', tmpsername).strip()
tmpsrname = re.sub('\s', '', tmpsrname).strip()
logger.fdebug('Comparing modified names: ' + tmpsrname + ' - to - ' + tmpsername)
if tmpsername.lower() == tmpsrname.lower():
logger.fdebug('Name matched successful: ' + sr['name'])
if str(sr['comicyear']) == str(theissdate):
logger.fdebug('Matched to : ' + str(theissdate))
matches.append(sr)
if len(matches) == 1:
logger.info('Narrowed down to one series as a direct match: ' + matches[0]['name'] + '[' + str(matches[0]['comicid']) + ']')
cid = matches[0]['comicid']
matched = True
else:
logger.info('Unable to determine a successful match at this time (this is still a WIP so it will eventually work). Not going to attempt auto-adding at this time.')
catch_words = ('the', 'and', '&', 'to')
for pos_match in search_results:
logger.info(pos_match)
length_match = len(pos_match['name']) / len(ser['ComicName'])
logger.fdebug('length match differential set for an allowance of 20%')
logger.fdebug('actual differential in length between result and series title: ' + str((length_match * 100)-100) + '%')
if ((length_match * 100)-100) > 20:
logger.fdebug('there are too many extra words to consider this as match for the given title. Ignoring this result.')
continue
new_match = pos_match['name'].lower()
split_series = ser['ComicName'].lower().split()
for cw in catch_words:
for x in new_match.split():
#logger.fdebug('comparing x: ' + str(x) + ' to cw: ' + str(cw))
if x == cw:
new_match = re.sub(x, '', new_match)
split_match = new_match.split()
word_match = 0
i = 0
for ss in split_series:
try:
matchword = split_match[i].lower()
except:
break
if any([x == matchword for x in catch_words]):
#logger.fdebug('[MW] common word detected of : ' + matchword)
word_match+=.5
elif any([cw == ss for cw in catch_words]):
#logger.fdebug('[CW] common word detected of : ' + matchword)
word_match+=.5
else:
try:
#will return word position in string.
#logger.fdebug('word match to position found in both strings at position : ' + str(split_match.index(ss)))
if split_match.index(ss) == split_series.index(ss):
word_match+=1
except ValueError:
break
i+=1
logger.fdebug('word match score of : ' + str(word_match) + ' / ' + str(len(split_series)))
if word_match == len(split_series) or (word_match / len(split_series)) > 80:
logger.fdebug('[' + pos_match['name'] + '] considered a match - word matching percentage is greater than 80%. Attempting to auto-add series into watchlist.')
cid = pos_match['comicid']
matched = True
if matched:
#we should probably load all additional issues for the series on the futureupcoming list that are marked as Wanted and then
#throw them to the importer as a tuple, and once imported the import can run the additional search against them.
#now we scan for additional issues of the same series on the upcoming list and mark them accordingly.
chkthewanted = []
chkwant = myDB.select("SELECT * FROM futureupcoming WHERE ComicName=? AND IssueNumber != '1' AND Status='Wanted'", [ser['ComicName']])
if chkwant is None:
logger.info('No extra issues to mark at this time for ' + ser['ComicName'])
else:
for chk in chkwant:
chkthewanted.append({"ComicName": chk['ComicName'],
"IssueDate": chk['IssueDate'],
"IssueNumber": chk['IssueNumber'], #this should be all #1's as the sql above limits the hits.
"Publisher": chk['Publisher'],
"Status": chk['Status']})
logger.info('Marking ' + str(len(chkthewanted)) + ' additional issues as Wanted from ' + ser['ComicName'] + ' series as requested.')
future_check_add(cid, ser, chkthewanted, theissdate)
else:
logger.info('No series information available as of yet for ' + ser['ComicName'] + '[#' + str(ser['IssueNumber']) + '] (' + str(theissdate) + ')')
continue
logger.info('Finished attempting to auto-add new series.')
return
def future_check_add(comicid, serinfo, chkthewanted=None, theissdate=None):
#In order to not error out when adding series with absolutely NO issue data, we need to 'fakeup' some values
#latestdate = the 'On sale' date from the futurepull-list OR the Shipping date if not available.
#latestiss = the IssueNumber for the first issue (this should always be #1, but might change at some point)
ser = serinfo
if theissdate is None:
theissdate = ser['IssueDate'][-4:]
if not theissdate.startswith('20'):
theissdate = ser['IssueDate'][:4]
latestissueinfo = []
latestissueinfo.append({"latestdate": ser['IssueDate'],
"latestiss": ser['IssueNumber']})
logger.fdebug('sending latestissueinfo from future as : ' + str(latestissueinfo))
chktheadd = importer.addComictoDB(comicid, "no", chkwant=chkthewanted, latestissueinfo=latestissueinfo, calledfrom="futurecheck")
if chktheadd != 'Exists':
logger.info('Sucessfully imported ' + ser['ComicName'] + ' (' + str(theissdate) + ')')
myDB = db.DBConnection()
myDB.action('DELETE from futureupcoming WHERE ComicName=?', [ser['ComicName']])
logger.info('Removed ' + ser['ComicName'] + ' (' + str(theissdate) + ') from the future upcoming list as it is now added.')
return
| 88,402 | Python | .py | 1,416 | 41.372175 | 714 | 0.489986 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,223 | config.py | evilhero_mylar/mylar/config.py | import itertools
from collections import OrderedDict
from operator import itemgetter
import os
import glob
import codecs
import shutil
import threading
import re
import ConfigParser
import mylar
from mylar import logger, helpers, encrypted
import errno
config = ConfigParser.SafeConfigParser()
_CONFIG_DEFINITIONS = OrderedDict({
#keyname, type, section, default
'CONFIG_VERSION': (int, 'General', 6),
'MINIMAL_INI': (bool, 'General', False),
'OLDCONFIG_VERSION': (str, 'General', None),
'AUTO_UPDATE': (bool, 'General', False),
'CACHE_DIR': (str, 'General', None),
'DYNAMIC_UPDATE': (int, 'General', 0),
'REFRESH_CACHE': (int, 'General', 7),
'ANNUALS_ON': (bool, 'General', False),
'SYNO_FIX': (bool, 'General', False),
'LAUNCH_BROWSER' : (bool, 'General', False),
'WANTED_TAB_OFF': (bool, 'General', False),
'ENABLE_RSS': (bool, 'General', False),
'SEARCH_DELAY' : (int, 'General', 1),
'GRABBAG_DIR': (str, 'General', None),
'HIGHCOUNT': (int, 'General', 0),
'MAINTAINSERIESFOLDER': (bool, 'General', False),
'DESTINATION_DIR': (str, 'General', None), #if M_D_D_ is enabled, this will be the DEFAULT for writing
'MULTIPLE_DEST_DIRS': (str, 'General', None), #Nothing will ever get written to these dirs - just for scanning, unless it's metatagging/renaming.
'CREATE_FOLDERS': (bool, 'General', True),
'DELETE_REMOVE_DIR': (bool, 'General', False),
'UPCOMING_SNATCHED': (bool, 'General', True),
'UPDATE_ENDED': (bool, 'General', False),
'LOCMOVE': (bool, 'General', False),
'NEWCOM_DIR': (str, 'General', None),
'FFTONEWCOM_DIR': (bool, 'General', False),
'FOLDER_SCAN_LOG_VERBOSE': (bool, 'General', False),
'INTERFACE': (str, 'General', 'default'),
'CORRECT_METADATA': (bool, 'General', False),
'MOVE_FILES': (bool, 'General', False),
'RENAME_FILES': (bool, 'General', False),
'FOLDER_FORMAT': (str, 'General', '$Series ($Year)'),
'FILE_FORMAT': (str, 'General', '$Series $Annual $Issue ($Year)'),
'REPLACE_SPACES': (bool, 'General', False),
'REPLACE_CHAR': (str, 'General', None),
'ZERO_LEVEL': (bool, 'General', False),
'ZERO_LEVEL_N': (str, 'General', None),
'LOWERCASE_FILENAMES': (bool, 'General', False),
'IGNORE_HAVETOTAL': (bool, 'General', False),
'IGNORE_TOTAL': (bool, 'General', False),
'SNATCHED_HAVETOTAL': (bool, 'General', False),
'FAILED_DOWNLOAD_HANDLING': (bool, 'General', False),
'FAILED_AUTO': (bool, 'General',False),
'PREFERRED_QUALITY': (int, 'General', 0),
'USE_MINSIZE': (bool, 'General', False),
'MINSIZE': (str, 'General', None),
'USE_MAXSIZE': (bool, 'General', False),
'MAXSIZE': (str, 'General', None),
'AUTOWANT_UPCOMING': (bool, 'General', True),
'AUTOWANT_ALL': (bool, 'General', False),
'COMIC_COVER_LOCAL': (bool, 'General', False),
'ADD_TO_CSV': (bool, 'General', True),
'SKIPPED2WANTED': (bool, 'General', False),
'READ2FILENAME': (bool, 'General', False),
'SEND2READ': (bool, 'General', False),
'NZB_STARTUP_SEARCH': (bool, 'General', False),
'UNICODE_ISSUENUMBER': (bool, 'General', False),
'CREATE_FOLDERS': (bool, 'General', True),
'ALTERNATE_LATEST_SERIES_COVERS': (bool, 'General', False),
'SHOW_ICONS': (bool, 'General', False),
'FORMAT_BOOKTYPE': (bool, 'General', False),
'CLEANUP_CACHE': (bool, 'General', False),
'SECURE_DIR': (str, 'General', None),
'ENCRYPT_PASSWORDS': (bool, 'General', False),
'RSS_CHECKINTERVAL': (int, 'Scheduler', 20),
'SEARCH_INTERVAL': (int, 'Scheduler', 360),
'DOWNLOAD_SCAN_INTERVAL': (int, 'Scheduler', 5),
'CHECK_GITHUB_INTERVAL' : (int, 'Scheduler', 360),
'ALT_PULL' : (int, 'Weekly', 2),
'PULL_REFRESH': (str, 'Weekly', None),
'WEEKFOLDER': (bool, 'Weekly', False),
'WEEKFOLDER_LOC': (str, 'Weekly', None),
'WEEKFOLDER_FORMAT': (int, 'Weekly', 0),
'INDIE_PUB': (int, 'Weekly', 75),
'BIGGIE_PUB': (int, 'Weekly', 55),
'PACK_0DAY_WATCHLIST_ONLY': (bool, 'Weekly', True),
'RESET_PULLIST_PAGINATION': (bool, 'Weekly', True),
'HTTP_PORT' : (int, 'Interface', 8090),
'HTTP_HOST' : (str, 'Interface', '0.0.0.0'),
'HTTP_USERNAME' : (str, 'Interface', None),
'HTTP_PASSWORD' : (str, 'Interface', None),
'HTTP_ROOT' : (str, 'Interface', '/'),
'ENABLE_HTTPS' : (bool, 'Interface', False),
'HTTPS_CERT' : (str, 'Interface', None),
'HTTPS_KEY' : (str, 'Interface', None),
'HTTPS_CHAIN' : (str, 'Interface', None),
'HTTPS_FORCE_ON' : (bool, 'Interface', False),
'HOST_RETURN' : (str, 'Interface', None),
'AUTHENTICATION' : (int, 'Interface', 0),
'LOGIN_TIMEOUT': (int, 'Interface', 43800),
'ALPHAINDEX': (bool, 'Interface', True),
'API_ENABLED' : (bool, 'API', False),
'API_KEY' : (str, 'API', None),
'CVAPI_RATE' : (int, 'CV', 2),
'COMICVINE_API': (str, 'CV', None),
'BLACKLISTED_PUBLISHERS' : (str, 'CV', None),
'CV_VERIFY': (bool, 'CV', True),
'CV_ONLY': (bool, 'CV', True),
'CV_ONETIMER': (bool, 'CV', True),
'CVINFO': (bool, 'CV', False),
'LOG_DIR' : (str, 'Logs', None),
'MAX_LOGSIZE' : (int, 'Logs', 10000000),
'MAX_LOGFILES': (int, 'Logs', 5),
'LOG_LEVEL': (int, 'Logs', 1),
'GIT_PATH' : (str, 'Git', None),
'GIT_USER' : (str, 'Git', 'evilhero'),
'GIT_BRANCH' : (str, 'Git', None),
'CHECK_GITHUB' : (bool, 'Git', False),
'CHECK_GITHUB_ON_STARTUP' : (bool, 'Git', False),
'ENFORCE_PERMS': (bool, 'Perms', True),
'CHMOD_DIR': (str, 'Perms', '0777'),
'CHMOD_FILE': (str, 'Perms', '0660'),
'CHOWNER': (str, 'Perms', None),
'CHGROUP': (str, 'Perms', None),
'ADD_COMICS': (bool, 'Import', False),
'COMIC_DIR': (str, 'Import', None),
'IMP_MOVE': (bool, 'Import', False),
'IMP_PATHS': (bool, 'Import', False),
'IMP_RENAME': (bool, 'Import', False),
'IMP_METADATA': (bool, 'Import', False), # should default to False - this is enabled for testing only.
'DUPECONSTRAINT': (str, 'Duplicates', None),
'DDUMP': (bool, 'Duplicates', False),
'DUPLICATE_DUMP': (str, 'Duplicates', None),
'DUPLICATE_DATED_FOLDERS': (bool, 'Duplicates', False),
'PROWL_ENABLED': (bool, 'Prowl', False),
'PROWL_PRIORITY': (int, 'Prowl', 0),
'PROWL_KEYS': (str, 'Prowl', None),
'PROWL_ONSNATCH': (bool, 'Prowl', False),
'PUSHOVER_ENABLED': (bool, 'PUSHOVER', False),
'PUSHOVER_PRIORITY': (int, 'PUSHOVER', 0),
'PUSHOVER_APIKEY': (str, 'PUSHOVER', None),
'PUSHOVER_DEVICE': (str, 'PUSHOVER', None),
'PUSHOVER_USERKEY': (str, 'PUSHOVER', None),
'PUSHOVER_ONSNATCH': (bool, 'PUSHOVER', False),
'BOXCAR_ENABLED': (bool, 'BOXCAR', False),
'BOXCAR_ONSNATCH': (bool, 'BOXCAR', False),
'BOXCAR_TOKEN': (str, 'BOXCAR', None),
'PUSHBULLET_ENABLED': (bool, 'PUSHBULLET', False),
'PUSHBULLET_APIKEY': (str, 'PUSHBULLET', None),
'PUSHBULLET_DEVICEID': (str, 'PUSHBULLET', None),
'PUSHBULLET_CHANNEL_TAG': (str, 'PUSHBULLET', None),
'PUSHBULLET_ONSNATCH': (bool, 'PUSHBULLET', False),
'TELEGRAM_ENABLED': (bool, 'TELEGRAM', False),
'TELEGRAM_TOKEN': (str, 'TELEGRAM', None),
'TELEGRAM_USERID': (str, 'TELEGRAM', None),
'TELEGRAM_ONSNATCH': (bool, 'TELEGRAM', False),
'SLACK_ENABLED': (bool, 'SLACK', False),
'SLACK_WEBHOOK_URL': (str, 'SLACK', None),
'SLACK_ONSNATCH': (bool, 'SLACK', False),
'EMAIL_ENABLED': (bool, 'Email', False),
'EMAIL_FROM': (str, 'Email', ''),
'EMAIL_TO': (str, 'Email', ''),
'EMAIL_SERVER': (str, 'Email', ''),
'EMAIL_USER': (str, 'Email', ''),
'EMAIL_PASSWORD': (str, 'Email', ''),
'EMAIL_PORT': (int, 'Email', 25),
'EMAIL_ENC': (int, 'Email', 0),
'EMAIL_ONGRAB': (bool, 'Email', True),
'EMAIL_ONPOST': (bool, 'Email', True),
'POST_PROCESSING': (bool, 'PostProcess', False),
'FILE_OPTS': (str, 'PostProcess', 'move'),
'SNATCHEDTORRENT_NOTIFY': (bool, 'PostProcess', False),
'LOCAL_TORRENT_PP': (bool, 'PostProcess', False),
'POST_PROCESSING_SCRIPT': (str, 'PostProcess', None),
'ENABLE_EXTRA_SCRIPTS': (bool, 'PostProcess', False),
'EXTRA_SCRIPTS': (str, 'PostProcess', None),
'ENABLE_SNATCH_SCRIPT': (bool, 'PostProcess', False),
'SNATCH_SCRIPT': (str, 'PostProcess', None),
'ENABLE_PRE_SCRIPTS': (bool, 'PostProcess', False),
'PRE_SCRIPTS': (str, 'PostProcess', None),
'ENABLE_CHECK_FOLDER': (bool, 'PostProcess', False),
'CHECK_FOLDER': (str, 'PostProcess', None),
'PROVIDER_ORDER': (str, 'Providers', None),
'USENET_RETENTION': (int, 'Providers', 1500),
'NZB_DOWNLOADER': (int, 'Client', 0), #0': sabnzbd, #1': nzbget, #2': blackhole
'TORRENT_DOWNLOADER': (int, 'Client', 0), #0': watchfolder, #1': uTorrent, #2': rTorrent, #3': transmission, #4': deluge, #5': qbittorrent
'SAB_HOST': (str, 'SABnzbd', None),
'SAB_USERNAME': (str, 'SABnzbd', None),
'SAB_PASSWORD': (str, 'SABnzbd', None),
'SAB_APIKEY': (str, 'SABnzbd', None),
'SAB_CATEGORY': (str, 'SABnzbd', None),
'SAB_PRIORITY': (str, 'SABnzbd', "Default"),
'SAB_TO_MYLAR': (bool, 'SABnzbd', False),
'SAB_DIRECTORY': (str, 'SABnzbd', None),
'SAB_VERSION': (str, 'SABnzbd', None),
'SAB_CLIENT_POST_PROCESSING': (bool, 'SABnzbd', False), #0/False: ComicRN.py, #1/True: Completed Download Handling
'NZBGET_HOST': (str, 'NZBGet', None),
'NZBGET_PORT': (str, 'NZBGet', None),
'NZBGET_USERNAME': (str, 'NZBGet', None),
'NZBGET_PASSWORD': (str, 'NZBGet', None),
'NZBGET_PRIORITY': (str, 'NZBGet', None),
'NZBGET_CATEGORY': (str, 'NZBGet', None),
'NZBGET_DIRECTORY': (str, 'NZBGet', None),
'NZBGET_CLIENT_POST_PROCESSING': (bool, 'NZBGet', False), #0/False: ComicRN.py, #1/True: Completed Download Handling
'BLACKHOLE_DIR': (str, 'Blackhole', None),
'NZBSU': (bool, 'NZBsu', False),
'NZBSU_UID': (str, 'NZBsu', None),
'NZBSU_APIKEY': (str, 'NZBsu', None),
'NZBSU_VERIFY': (bool, 'NZBsu', True),
'DOGNZB': (bool, 'DOGnzb', False),
'DOGNZB_APIKEY': (str, 'DOGnzb', None),
'DOGNZB_VERIFY': (bool, 'DOGnzb', True),
'NEWZNAB': (bool, 'Newznab', False),
'EXTRA_NEWZNABS': (str, 'Newznab', ""),
'ENABLE_TORZNAB': (bool, 'Torznab', False),
'EXTRA_TORZNABS': (str, 'Torznab', ""),
'TORZNAB_NAME': (str, 'Torznab', None),
'TORZNAB_HOST': (str, 'Torznab', None),
'TORZNAB_APIKEY': (str, 'Torznab', None),
'TORZNAB_CATEGORY': (str, 'Torznab', None),
'TORZNAB_VERIFY': (bool, 'Torznab', False),
'EXPERIMENTAL': (bool, 'Experimental', False),
'ALTEXPERIMENTAL': (bool, 'Experimental', False),
'TAB_ENABLE': (bool, 'Tablet', False),
'TAB_HOST': (str, 'Tablet', None),
'TAB_USER': (str, 'Tablet', None),
'TAB_PASS': (str, 'Tablet', None),
'TAB_DIRECTORY': (str, 'Tablet', None),
'STORYARCDIR': (bool, 'StoryArc', False),
'COPY2ARCDIR': (bool, 'StoryArc', False),
'ARC_FOLDERFORMAT': (str, 'StoryArc', None),
'ARC_FILEOPS': (str, 'StoryArc', 'copy'),
'UPCOMING_STORYARCS': (bool, 'StoryArc', False),
'SEARCH_STORYARCS': (bool, 'StoryArc', False),
'LOCMOVE': (bool, 'Update', False),
'NEWCOM_DIR': (str, 'Update', None),
'FFTONEWCOM_DIR': (bool, 'Update', False),
'ENABLE_META': (bool, 'Metatagging', False),
'CMTAGGER_PATH': (str, 'Metatagging', None),
'CBR2CBZ_ONLY': (bool, 'Metatagging', False),
'CT_TAG_CR': (bool, 'Metatagging', True),
'CT_TAG_CBL': (bool, 'Metatagging', True),
'CT_CBZ_OVERWRITE': (bool, 'Metatagging', False),
'UNRAR_CMD': (str, 'Metatagging', None),
'CT_SETTINGSPATH': (str, 'Metatagging', None),
'CMTAG_VOLUME': (bool, 'Metatagging', True),
'CMTAG_START_YEAR_AS_VOLUME': (bool, 'Metatagging', False),
'SETDEFAULTVOLUME': (bool, 'Metatagging', False),
'ENABLE_TORRENTS': (bool, 'Torrents', False),
'ENABLE_TORRENT_SEARCH': (bool, 'Torrents', False),
'MINSEEDS': (int, 'Torrents', 0),
'ALLOW_PACKS': (bool, 'Torrents', False),
'ENABLE_PUBLIC': (bool, 'Torrents', False),
'PUBLIC_VERIFY': (bool, 'Torrents', True),
'ENABLE_DDL': (bool, 'DDL', False),
'ALLOW_PACKS': (bool, 'DDL', False),
'DDL_LOCATION': (str, 'DDL', None),
'DDL_AUTORESUME': (bool, 'DDL', True),
'AUTO_SNATCH': (bool, 'AutoSnatch', False),
'AUTO_SNATCH_SCRIPT': (str, 'AutoSnatch', None),
'PP_SSHHOST': (str, 'AutoSnatch', None),
'PP_SSHPORT': (str, 'AutoSnatch', 22),
'PP_SSHUSER': (str, 'AutoSnatch', None),
'PP_SSHPASSWD': (str, 'AutoSnatch', None),
'PP_SSHLOCALCD': (str, 'AutoSnatch', None),
'PP_SSHKEYFILE': (str, 'AutoSnatch', None),
'TORRENT_LOCAL': (bool, 'Watchdir', False),
'LOCAL_WATCHDIR': (str, 'Watchdir', None),
'TORRENT_SEEDBOX': (bool, 'Seedbox', False),
'SEEDBOX_HOST': (str, 'Seedbox', None),
'SEEDBOX_PORT': (str, 'Seedbox', None),
'SEEDBOX_USER': (str, 'Seedbox', None),
'SEEDBOX_PASS': (str, 'Seedbox', None),
'SEEDBOX_WATCHDIR': (str, 'Seedbox', None),
'ENABLE_32P': (bool, '32P', False),
'SEARCH_32P': (bool, '32P', False), #0': use WS to grab torrent groupings, #1': use 32P to grab torrent groupings
'DEEP_SEARCH_32P': (bool, '32P', False), #0': do not take multiple search series results & use ref32p if available, #1= search each search series result for valid $
'MODE_32P': (bool, '32P', False), #0': legacymode, #1': authmode
'RSSFEED_32P': (str, '32P', None),
'PASSKEY_32P': (str, '32P', None),
'USERNAME_32P': (str, '32P', None),
'PASSWORD_32P': (str, '32P', None),
'VERIFY_32P': (bool, '32P', True),
'RTORRENT_HOST': (str, 'Rtorrent', None),
'RTORRENT_AUTHENTICATION': (str, 'Rtorrent', 'basic'),
'RTORRENT_RPC_URL': (str, 'Rtorrent', None),
'RTORRENT_SSL': (bool, 'Rtorrent', False),
'RTORRENT_VERIFY': (bool, 'Rtorrent', False),
'RTORRENT_CA_BUNDLE': (str, 'Rtorrent', None),
'RTORRENT_USERNAME': (str, 'Rtorrent', None),
'RTORRENT_PASSWORD': (str, 'Rtorrent', None),
'RTORRENT_STARTONLOAD': (bool, 'Rtorrent', False),
'RTORRENT_LABEL': (str, 'Rtorrent', None),
'RTORRENT_DIRECTORY': (str, 'Rtorrent', None),
'UTORRENT_HOST': (str, 'uTorrent', None),
'UTORRENT_USERNAME': (str, 'uTorrent', None),
'UTORRENT_PASSWORD': (str, 'uTorrent', None),
'UTORRENT_LABEL': (str, 'uTorrent', None),
'TRANSMISSION_HOST': (str, 'Transmission', None),
'TRANSMISSION_USERNAME': (str, 'Transmission', None),
'TRANSMISSION_PASSWORD': (str, 'Transmission', None),
'TRANSMISSION_DIRECTORY': (str, 'Transmission', None),
'DELUGE_HOST': (str, 'Deluge', None),
'DELUGE_USERNAME': (str, 'Deluge', None),
'DELUGE_PASSWORD': (str, 'Deluge', None),
'DELUGE_LABEL': (str, 'Deluge', None),
'DELUGE_PAUSE': (bool, 'Deluge', False),
'DELUGE_DOWNLOAD_DIRECTORY': (str, 'Deluge', ""),
'DELUGE_DONE_DIRECTORY': (str, 'Deluge', ""),
'QBITTORRENT_HOST': (str, 'qBittorrent', None),
'QBITTORRENT_USERNAME': (str, 'qBittorrent', None),
'QBITTORRENT_PASSWORD': (str, 'qBittorrent', None),
'QBITTORRENT_LABEL': (str, 'qBittorrent', None),
'QBITTORRENT_FOLDER': (str, 'qBittorrent', None),
'QBITTORRENT_LOADACTION': (str, 'qBittorrent', 'default'), #default, force_start, paused
'OPDS_ENABLE': (bool, 'OPDS', False),
'OPDS_AUTHENTICATION': (bool, 'OPDS', False),
'OPDS_USERNAME': (str, 'OPDS', None),
'OPDS_PASSWORD': (str, 'OPDS', None),
'OPDS_METAINFO': (bool, 'OPDS', False),
'OPDS_PAGESIZE': (int, 'OPDS', 30),
})
_BAD_DEFINITIONS = OrderedDict({
#for those items that were in wrong sections previously, or sections that are no longer present...
#using this method, old values are able to be transfered to the new config items properly.
#keyname, section, oldkeyname
#ie. 'TEST_VALUE': ('TEST', 'TESTVALUE')
'SAB_CLIENT_POST_PROCESSING': ('SABnbzd', None),
'ENABLE_PUBLIC': ('Torrents', 'ENABLE_TPSE'),
'PUBLIC_VERIFY': ('Torrents', 'TPSE_VERIFY'),
})
class Config(object):
def __init__(self, config_file):
# initalize the config...
self._config_file = config_file
def config_vals(self, update=False):
if update is False:
if os.path.isfile(self._config_file):
self.config = config.readfp(codecs.open(self._config_file, 'r', 'utf8')) #read(self._config_file)
#check for empty config / new config
count = sum(1 for line in open(self._config_file))
else:
count = 0
self.newconfig = 10
if count == 0:
CONFIG_VERSION = 0
MINIMALINI = False
else:
# get the config version first, since we need to know.
try:
CONFIG_VERSION = config.getint('General', 'config_version')
except:
CONFIG_VERSION = 0
try:
MINIMALINI = config.getboolean('General', 'minimal_ini')
except:
MINIMALINI = False
setattr(self, 'CONFIG_VERSION', CONFIG_VERSION)
setattr(self, 'MINIMAL_INI', MINIMALINI)
config_values = []
for k,v in _CONFIG_DEFINITIONS.iteritems():
xv = []
xv.append(k)
for x in v:
if x is None:
x = 'None'
xv.append(x)
value = self.check_setting(xv)
for b, bv in _BAD_DEFINITIONS.iteritems():
try:
if config.has_section(bv[0]) and any([b == k, bv[1] is None]):
cvs = xv
if bv[1] is None:
ckey = k
else:
ckey = bv[1]
corevalues = [ckey if x == 0 else x for x in cvs]
corevalues = [bv[0] if x == corevalues.index(bv[0]) else x for x in cvs]
value = self.check_setting(corevalues)
if bv[1] is None:
config.remove_option(bv[0], ckey.lower())
config.remove_section(bv[0])
else:
config.remove_option(bv[0], bv[1].lower())
break
except:
pass
if all([k != 'CONFIG_VERSION', k != 'MINIMAL_INI']):
try:
if v[0] == str and any([value == "", value is None, len(value) == 0, value == 'None']):
value = v[2]
except:
value = v[2]
try:
if v[0] == bool:
value = self.argToBool(value)
except:
value = self.argToBool(v[2])
try:
if all([v[0] == int, str(value).isdigit()]):
value = int(value)
except:
value = v[2]
setattr(self, k, value)
try:
#make sure interpolation isn't being used, so we can just escape the % character
if v[0] == str:
value = value.replace('%', '%%')
except Exception as e:
pass
#just to ensure defaults are properly set...
if any([value is None, value == 'None']):
value = v[0](v[2])
if all([self.MINIMAL_INI is True, str(value) != str(v[2])]) or self.MINIMAL_INI is False:
try:
config.add_section(v[1])
except ConfigParser.DuplicateSectionError:
pass
else:
try:
if config.has_section(v[1]):
config.remove_option(v[1], k.lower())
except ConfigParser.NoSectionError:
continue
if all([config.has_section(v[1]), self.MINIMAL_INI is False]) or all([self.MINIMAL_INI is True, str(value) != str(v[2]), config.has_section(v[1])]):
config.set(v[1], k.lower(), str(value))
else:
try:
if config.has_section(v[1]):
config.remove_option(v[1], k.lower())
if len(dict(config.items(v[1]))) == 0:
config.remove_section(v[1])
except ConfigParser.NoSectionError:
continue
else:
if k == 'CONFIG_VERSION':
config.remove_option('General', 'dbuser')
config.remove_option('General', 'dbpass')
config.remove_option('General', 'dbchoice')
config.remove_option('General', 'dbname')
elif k == 'MINIMAL_INI':
config.set(v[1], k.lower(), str(self.MINIMAL_INI))
def read(self, startup=False):
self.config_vals()
setattr(self, 'EXTRA_NEWZNABS', self.get_extra_newznabs())
setattr(self, 'EXTRA_TORZNABS', self.get_extra_torznabs())
if any([self.CONFIG_VERSION == 0, self.CONFIG_VERSION < self.newconfig]):
try:
shutil.move(self._config_file, os.path.join(mylar.DATA_DIR, 'config.ini.backup'))
except:
print('Unable to make proper backup of config file in %s' % os.path.join(mylar.DATA_DIR, 'config.ini.backup'))
if self.CONFIG_VERSION < 10:
print('Attempting to update configuration..')
#8-torznab multiple entries merged into extra_torznabs value
#9-remote rtorrent ssl option
#10-encryption of all keys/passwords.
self.config_update()
setattr(self, 'CONFIG_VERSION', str(self.newconfig))
config.set('General', 'CONFIG_VERSION', str(self.newconfig))
self.writeconfig()
else:
self.provider_sequence()
if startup is True:
if self.LOG_DIR is None:
self.LOG_DIR = os.path.join(mylar.DATA_DIR, 'logs')
if not os.path.exists(self.LOG_DIR):
try:
os.makedirs(self.LOG_DIR)
except OSError:
if not mylar.QUIET:
self.LOG_DIR = None
print('Unable to create the log directory. Logging to screen only.')
# Start the logger, silence console logging if we need to
if logger.LOG_LANG.startswith('en'):
logger.initLogger(console=not mylar.QUIET, log_dir=self.LOG_DIR, max_logsize=self.MAX_LOGSIZE, max_logfiles=self.MAX_LOGFILES, loglevel=mylar.LOG_LEVEL)
else:
if self.LOG_LEVEL != mylar.LOG_LEVEL:
print('Logging level over-ridden by startup value. Changing from %s to %s' % (self.LOG_LEVEL, mylar.LOG_LEVEL))
logger.mylar_log.initLogger(loglevel=mylar.LOG_LEVEL, log_dir=self.LOG_DIR, max_logsize=self.MAX_LOGSIZE, max_logfiles=self.MAX_LOGFILES)
self.configure(startup=startup)
return self
def config_update(self):
print('Updating Configuration from %s to %s' % (self.CONFIG_VERSION, self.newconfig))
if self.CONFIG_VERSION < 8:
print('Checking for existing torznab configuration...')
if not any([self.TORZNAB_NAME is None, self.TORZNAB_HOST is None, self.TORZNAB_APIKEY is None, self.TORZNAB_CATEGORY is None]):
torznabs =[(self.TORZNAB_NAME, self.TORZNAB_HOST, self.TORZNAB_VERIFY, self.TORZNAB_APIKEY, self.TORZNAB_CATEGORY, str(int(self.ENABLE_TORZNAB)))]
setattr(self, 'EXTRA_TORZNABS', torznabs)
config.set('Torznab', 'EXTRA_TORZNABS', str(torznabs))
print('Successfully converted existing torznab for multiple configuration allowance. Removing old references.')
else:
print('No existing torznab configuration found. Just removing config references at this point..')
config.remove_option('Torznab', 'torznab_name')
config.remove_option('Torznab', 'torznab_host')
config.remove_option('Torznab', 'torznab_verify')
config.remove_option('Torznab', 'torznab_apikey')
config.remove_option('Torznab', 'torznab_category')
print('Successfully removed outdated config entries.')
if self.newconfig < 9:
#rejig rtorrent settings due to change.
try:
if all([self.RTORRENT_SSL is True, not self.RTORRENT_HOST.startswith('http')]):
self.RTORRENT_HOST = 'https://' + self.RTORRENT_HOST
config.set('Rtorrent', 'rtorrent_host', self.RTORRENT_HOST)
except:
pass
config.remove_option('Rtorrent', 'rtorrent_ssl')
print('Successfully removed oudated config entries.')
if self.newconfig < 10:
#encrypt all passwords / apikeys / usernames in ini file.
#leave non-ini items (ie. memory) as un-encrypted items.
try:
if self.ENCRYPT_PASSWORDS is True:
self.encrypt_items(mode='encrypt', updateconfig=True)
except Exception as e:
print('Error: %s' % e)
print('Successfully updated config to version 10 ( password / apikey - .ini encryption )')
print('Configuration upgraded to version %s' % self.newconfig)
def check_section(self, section, key):
""" Check if INI section exists, if not create it """
if config.has_section(section):
return True
else:
return False
def argToBool(self, argument):
_arg = argument.strip().lower() if isinstance(argument, basestring) else argument
if _arg in (1, '1', 'on', 'true', True):
return True
elif _arg in (0, '0', 'off', 'false', False):
return False
return argument
def check_setting(self, key):
""" Cast any value in the config to the right type or use the default """
keyname = key[0].upper()
inikey = key[0].lower()
definition_type = key[1]
section = key[2]
default = key[3]
myval = self.check_config(definition_type, section, inikey, default)
if myval['status'] is False:
if self.CONFIG_VERSION == 6 or (config.has_section('Torrents') and any([inikey == 'auto_snatch', inikey == 'auto_snatch_script'])):
chkstatus = False
if config.has_section('Torrents'):
myval = self.check_config(definition_type, 'Torrents', inikey, default)
if myval['status'] is True:
chkstatus = True
try:
config.remove_option('Torrents', inikey)
except ConfigParser.NoSectionError:
pass
if all([chkstatus is False, config.has_section('General')]):
myval = self.check_config(definition_type, 'General', inikey, default)
if myval['status'] is True:
config.remove_option('General', inikey)
else:
#print 'no key found in ini - setting to default value of %s' % definition_type(default)
#myval = {'value': definition_type(default)}
pass
else:
myval = {'value': definition_type(default)}
#if all([myval['value'] is not None, myval['value'] != '', myval['value'] != 'None']):
#if default != myval['value']:
# print '%s : %s' % (keyname, myval['value'])
#else:
# print 'NEW CONFIGURATION SETTING %s : %s' % (keyname, myval['value'])
return myval['value']
def check_config(self, definition_type, section, inikey, default):
try:
if definition_type == str:
myval = {'status': True, 'value': config.get(section, inikey)}
elif definition_type == int:
myval = {'status': True, 'value': config.getint(section, inikey)}
elif definition_type == bool:
myval = {'status': True, 'value': config.getboolean(section, inikey)}
except Exception:
if definition_type == str:
try:
myval = {'status': True, 'value': config.get(section, inikey, raw=True)}
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
myval = {'status': False, 'value': None}
else:
myval = {'status': False, 'value': None}
return myval
def _define(self, name):
key = name.upper()
ini_key = name.lower()
definition = _CONFIG_DEFINITIONS[key]
if len(definition) == 3:
definition_type, section, default = definition
elif len(definition) == 4:
definition_type, section, _, default = definition
return key, definition_type, section, ini_key, default
def process_kwargs(self, kwargs):
"""
Given a big bunch of key value pairs, apply them to the ini.
"""
for name, value in kwargs.items():
if not any([(name.startswith('newznab') and name[-1].isdigit()), name.startswith('torznab') and name[-1].isdigit()]):
key, definition_type, section, ini_key, default = self._define(name)
if definition_type == str:
try:
if any([value == "", value is None, len(value) == 0]):
value = default
else:
value = str(value)
except:
value = default
try:
if definition_type == bool:
value = self.argToBool(value)
except:
value = self.argToBool(default)
try:
if all([definition_type == int, str(value).isdigit()]):
value = int(value)
except:
value = default
#just to ensure defaults are properly set...
if any([value is None, value == 'None']):
value = definition_type(default)
if key != 'MINIMAL_INI':
if value == 'None': nv = None
else: nv = definition_type(value)
setattr(self, key, nv)
#print('writing config value...[%s][%s] key: %s / ini_key: %s / value: %s [%s]' % (definition_type, section, key, ini_key, value, default))
if all([self.MINIMAL_INI is True, definition_type(value) != definition_type(default)]) or self.MINIMAL_INI is False:
try:
config.add_section(section)
except ConfigParser.DuplicateSectionError:
pass
else:
try:
if config.has_section(section):
config.remove_option(section, ini_key)
if len(dict(config.items(section))) == 0:
config.remove_section(section)
except ConfigParser.NoSectionError:
continue
if any([value is None, value == ""]):
value = definition_type(default)
if config.has_section(section) and (all([self.MINIMAL_INI is True, definition_type(value) != definition_type(default)]) or self.MINIMAL_INI is False):
try:
if definition_type == str:
value = value.replace('%', '%%')
except Exception as e:
pass
config.set(section, ini_key, str(value))
else:
config.set(section, ini_key, str(self.MINIMAL_INI))
else:
pass
if self.ENCRYPT_PASSWORDS is True:
self.encrypt_items(mode='encrypt')
def writeconfig(self, values=None):
logger.fdebug("Writing configuration to file")
self.provider_sequence()
config.set('Newznab', 'extra_newznabs', ', '.join(self.write_extras(self.EXTRA_NEWZNABS)))
config.set('Torznab', 'extra_torznabs', ', '.join(self.write_extras(self.EXTRA_TORZNABS)))
###this should be moved elsewhere...
if type(self.BLACKLISTED_PUBLISHERS) != list:
if self.BLACKLISTED_PUBLISHERS is None:
bp = 'None'
else:
bp = ', '.join(self.write_extras(self.BLACKLISTED_PUBLISHERS))
config.set('CV', 'blacklisted_publishers', bp)
else:
config.set('CV', 'blacklisted_publishers', ', '.join(self.BLACKLISTED_PUBLISHERS))
###
config.set('General', 'dynamic_update', str(self.DYNAMIC_UPDATE))
if values is not None:
self.process_kwargs(values)
try:
with codecs.open(self._config_file, encoding='utf8', mode='w+') as configfile:
config.write(configfile)
logger.fdebug('Configuration written to disk.')
except IOError as e:
logger.warn("Error writing configuration file: %s", e)
def encrypt_items(self, mode='encrypt', updateconfig=False):
encryption_list = OrderedDict({
#key section key value
'HTTP_PASSWORD': ('Interface', 'http_password', self.HTTP_PASSWORD),
'SAB_PASSWORD': ('SABnzbd', 'sab_password', self.SAB_PASSWORD),
'SAB_APIKEY': ('SABnzbd', 'sab_apikey', self.SAB_APIKEY),
'NZBGET_PASSWORD': ('NZBGet', 'nzbget_password', self.NZBGET_PASSWORD),
'NZBSU_APIKEY': ('NZBsu', 'nzbsu_apikey', self.NZBSU_APIKEY),
'DOGNZB_APIKEY': ('DOGnzb', 'dognzb_apikey', self.DOGNZB_APIKEY),
'UTORRENT_PASSWORD': ('uTorrent', 'utorrent_password', self.UTORRENT_PASSWORD),
'TRANSMISSION_PASSWORD': ('Transmission', 'transmission_password', self.TRANSMISSION_PASSWORD),
'DELUGE_PASSWORD': ('Deluge', 'deluge_password', self.DELUGE_PASSWORD),
'QBITTORRENT_PASSWORD': ('qBittorrent', 'qbittorrent_password', self.QBITTORRENT_PASSWORD),
'RTORRENT_PASSWORD': ('Rtorrent', 'rtorrent_password', self.RTORRENT_PASSWORD),
'PROWL_KEYS': ('Prowl', 'prowl_keys', self.PROWL_KEYS),
'PUSHOVER_APIKEY': ('PUSHOVER', 'pushover_apikey', self.PUSHOVER_APIKEY),
'PUSHOVER_USERKEY': ('PUSHOVER', 'pushover_userkey', self.PUSHOVER_USERKEY),
'BOXCAR_TOKEN': ('BOXCAR', 'boxcar_token', self.BOXCAR_TOKEN),
'PUSHBULLET_APIKEY': ('PUSHBULLET', 'pushbullet_apikey', self.PUSHBULLET_APIKEY),
'TELEGRAM_TOKEN': ('TELEGRAM', 'telegram_token', self.TELEGRAM_TOKEN),
'COMICVINE_API': ('CV', 'comicvine_api', self.COMICVINE_API),
'PASSWORD_32P': ('32P', 'password_32p', self.PASSWORD_32P),
'PASSKEY_32P': ('32P', 'passkey_32p', self.PASSKEY_32P),
'USERNAME_32P': ('32P', 'username_32p', self.USERNAME_32P),
'SEEDBOX_PASS': ('Seedbox', 'seedbox_pass', self.SEEDBOX_PASS),
'TAB_PASS': ('Tablet', 'tab_pass', self.TAB_PASS),
'API_KEY': ('API', 'api_key', self.API_KEY),
'OPDS_PASSWORD': ('OPDS', 'opds_password', self.OPDS_PASSWORD),
'PP_SSHPASSWD': ('AutoSnatch', 'pp_sshpasswd', self.PP_SSHPASSWD),
})
new_encrypted = 0
for k,v in encryption_list.iteritems():
value = []
for x in v:
value.append(x)
if value[2] is not None:
if value[2][:5] == '^~$z$':
if mode == 'decrypt':
hp = encrypted.Encryptor(value[2])
decrypted_password = hp.decrypt_it()
if decrypted_password['status'] is False:
logger.warn('Password unable to decrypt - you might have to manually edit the ini for %s to reset the value' % value[1])
else:
if k != 'HTTP_PASSWORD':
setattr(self, k, decrypted_password['password'])
config.set(value[0], value[1], decrypted_password['password'])
else:
if k == 'HTTP_PASSWORD':
hp = encrypted.Encryptor(value[2])
decrypted_password = hp.decrypt_it()
if decrypted_password['status'] is False:
logger.warn('Password unable to decrypt - you might have to manually edit the ini for %s to reset the value' % value[1])
else:
setattr(self, k, decrypted_password['password'])
else:
hp = encrypted.Encryptor(value[2])
encrypted_password = hp.encrypt_it()
if encrypted_password['status'] is False:
logger.warn('Unable to encrypt password for %s - it has not been encrypted. Keeping it as it is.' % value[1])
else:
if k == 'HTTP_PASSWORD':
#make sure we set the http_password for signon to the encrypted value otherwise won't match
setattr(self, k, encrypted_password['password'])
config.set(value[0], value[1], encrypted_password['password'])
new_encrypted+=1
def configure(self, update=False, startup=False):
#force alt_pull = 2 on restarts regardless of settings
if self.ALT_PULL != 2:
self.ALT_PULL = 2
config.set('Weekly', 'alt_pull', str(self.ALT_PULL))
#force off public torrents usage as currently broken.
self.ENABLE_PUBLIC = False
try:
if not any([self.SAB_HOST is None, self.SAB_HOST == '', 'http://' in self.SAB_HOST[:7], 'https://' in self.SAB_HOST[:8]]):
self.SAB_HOST = 'http://' + self.SAB_HOST
if self.SAB_HOST.endswith('/'):
logger.fdebug("Auto-correcting trailing slash in SABnzbd url (not required)")
self.SAB_HOST = self.SAB_HOST[:-1]
except:
pass
if any([self.HTTP_ROOT is None, self.HTTP_ROOT == '/']):
self.HTTP_ROOT = '/'
else:
if not self.HTTP_ROOT.endswith('/'):
self.HTTP_ROOT += '/'
if not update:
logger.fdebug('Log dir: %s' % self.LOG_DIR)
if self.LOG_DIR is None:
self.LOG_DIR = os.path.join(mylar.DATA_DIR, 'logs')
if not os.path.exists(self.LOG_DIR):
try:
os.makedirs(self.LOG_DIR)
except OSError:
if not mylar.QUIET:
logger.warn('Unable to create the log directory. Logging to screen only.')
# if not update:
# logger.fdebug('[Cache Check] Cache directory currently set to : ' + self.CACHE_DIR)
# Put the cache dir in the data dir for now
if not self.CACHE_DIR:
self.CACHE_DIR = os.path.join(str(mylar.DATA_DIR), 'cache')
if not update:
logger.fdebug('[Cache Check] Cache directory not found in configuration. Defaulting location to : ' + self.CACHE_DIR)
if not os.path.exists(self.CACHE_DIR):
try:
os.makedirs(self.CACHE_DIR)
except OSError:
logger.error('[Cache Check] Could not create cache dir. Check permissions of datadir: ' + mylar.DATA_DIR)
if not self.SECURE_DIR:
self.SECURE_DIR = os.path.join(mylar.DATA_DIR, '.secure')
if not os.path.exists(self.SECURE_DIR):
try:
os.makedirs(self.SECURE_DIR)
except OSError:
logger.error('[Secure DIR Check] Could not create secure directory. Check permissions of datadir: ' + mylar.DATA_DIR)
#make sure the cookies.dat file is not in cache
for f in glob.glob(os.path.join(self.CACHE_DIR, '.32p_cookies.dat')):
try:
if os.path.isfile(f):
shutil.move(f, os.path.join(self.SECURE_DIR, '.32p_cookies.dat'))
except Exception as e:
logger.error('SECURE-DIR-MOVE] Unable to move cookies file into secure location. This is a fatal error.')
sys.exit()
if self.CLEANUP_CACHE is True:
logger.fdebug('[Cache Cleanup] Cache Cleanup initiated. Will delete items from cache that are no longer needed.')
cache_types = ['*.nzb', '*.torrent', '*.zip', '*.html', 'mylar_*']
cntr = 0
for x in cache_types:
for f in glob.glob(os.path.join(self.CACHE_DIR,x)):
try:
if os.path.isdir(f):
shutil.rmtree(f)
else:
os.remove(f)
except Exception as e:
logger.warn('[ERROR] Unable to remove %s from cache. Could be a possible permissions issue ?' % f)
cntr+=1
if cntr > 1:
logger.fdebug('[Cache Cleanup] Cache Cleanup finished. Cleaned %s items' % cntr)
else:
logger.fdebug('[Cache Cleanup] Cache Cleanup finished. Nothing to clean!')
if all([self.GRABBAG_DIR is None, self.DESTINATION_DIR is not None]):
self.GRABBAG_DIR = os.path.join(self.DESTINATION_DIR, 'Grabbag')
logger.fdebug('[Grabbag Directory] Setting One-Off directory to default location: %s' % self.GRABBAG_DIR)
## Sanity checking
if any([self.COMICVINE_API is None, self.COMICVINE_API == 'None', self.COMICVINE_API == '']):
logger.error('No User Comicvine API key specified. I will not work very well due to api limits - http://api.comicvine.com/ and get your own free key.')
self.COMICVINE_API = None
if self.SEARCH_INTERVAL < 360:
logger.fdebug('Search interval too low. Resetting to 6 hour minimum')
self.SEARCH_INTERVAL = 360
if self.SEARCH_DELAY < 1:
logger.fdebug("Minimum search delay set for 1 minute to avoid hammering.")
self.SEARCH_DELAY = 1
if self.RSS_CHECKINTERVAL < 20:
logger.fdebug("Minimum RSS Interval Check delay set for 20 minutes to avoid hammering.")
self.RSS_CHECKINTERVAL = 20
if self.ENABLE_RSS is True and mylar.RSS_STATUS == 'Paused':
mylar.RSS_STATUS = 'Waiting'
elif self.ENABLE_RSS is False and mylar.RSS_STATUS == 'Waiting':
mylar.RSS_STATUS = 'Paused'
if not helpers.is_number(self.CHMOD_DIR):
logger.fdebug("CHMOD Directory value is not a valid numeric - please correct. Defaulting to 0777")
self.CHMOD_DIR = '0777'
if not helpers.is_number(self.CHMOD_FILE):
logger.fdebug("CHMOD File value is not a valid numeric - please correct. Defaulting to 0660")
self.CHMOD_FILE = '0660'
if self.FILE_OPTS is None:
self.FILE_OPTS = 'move'
if any([self.FILE_OPTS == 'hardlink', self.FILE_OPTS == 'softlink']):
#we can't have metatagging enabled with hard/soft linking. Forcibly disable it here just in case it's set on load.
self.ENABLE_META = False
if self.BLACKLISTED_PUBLISHERS is not None and type(self.BLACKLISTED_PUBLISHERS) == unicode:
setattr(self, 'BLACKLISTED_PUBLISHERS', self.BLACKLISTED_PUBLISHERS.split(', '))
if all([self.AUTHENTICATION == 0, self.HTTP_USERNAME is not None, self.HTTP_PASSWORD is not None]):
#set it to the default login prompt if nothing selected.
self.AUTHENTICATION = 1
elif all([self.HTTP_USERNAME is None, self.HTTP_PASSWORD is None]):
self.AUTHENTICATION = 0
if self.ENCRYPT_PASSWORDS is True:
self.encrypt_items(mode='decrypt')
if all([self.IGNORE_TOTAL is True, self.IGNORE_HAVETOTAL is True]):
self.IGNORE_TOTAL = False
self.IGNORE_HAVETOTAL = False
logger.warn('You cannot have both ignore_total and ignore_havetotal enabled in the config.ini at the same time. Set only ONE to true - disabling both until this is resolved.')
#comictagger - force to use included version if option is enabled.
if self.ENABLE_META:
mylar.CMTAGGER_PATH = mylar.PROG_DIR
#we need to make sure the default folder setting for the comictagger settings exists so things don't error out
mylar.CT_SETTINGSPATH = os.path.join(mylar.PROG_DIR, 'lib', 'comictaggerlib', 'ct_settings')
if not update:
logger.fdebug('Setting ComicTagger settings default path to : ' + mylar.CT_SETTINGSPATH)
if not os.path.exists(mylar.CT_SETTINGSPATH):
try:
os.mkdir(mylar.CT_SETTINGSPATH)
except OSError,e:
if e.errno != errno.EEXIST:
logger.error('Unable to create setting directory for ComicTagger. This WILL cause problems when tagging.')
else:
logger.fdebug('Successfully created ComicTagger Settings location.')
#make sure queues are running here...
if startup is False:
if self.POST_PROCESSING is True and ( all([self.NZB_DOWNLOADER == 0, self.SAB_CLIENT_POST_PROCESSING is True]) or all([self.NZB_DOWNLOADER == 1, self.NZBGET_CLIENT_POST_PROCESSING is True]) ):
mylar.queue_schedule('nzb_queue', 'start')
elif self.POST_PROCESSING is True and ( all([self.NZB_DOWNLOADER == 0, self.SAB_CLIENT_POST_PROCESSING is False]) or all([self.NZB_DOWNLOADER == 1, self.NZBGET_CLIENT_POST_PROCESSING is False]) ):
mylar.queue_schedule('nzb_queue', 'stop')
if self.ENABLE_DDL is True:
mylar.queue_schedule('ddl_queue', 'start')
elif self.ENABLE_DDL is False:
mylar.queue_schedule('ddl_queue', 'stop')
if not self.DDL_LOCATION:
self.DDL_LOCATION = self.CACHE_DIR
if self.ENABLE_DDL is True:
logger.info('Setting DDL Location set to : %s' % self.DDL_LOCATION)
if self.MODE_32P is False and self.RSSFEED_32P is not None:
mylar.KEYS_32P = self.parse_32pfeed(self.RSSFEED_32P)
if self.AUTO_SNATCH is True and self.AUTO_SNATCH_SCRIPT is None:
setattr(self, 'AUTO_SNATCH_SCRIPT', os.path.join(mylar.PROG_DIR, 'post-processing', 'torrent-auto-snatch', 'getlftp.sh'))
config.set('AutoSnatch', 'auto_snatch_script', self.AUTO_SNATCH_SCRIPT)
mylar.USE_SABNZBD = False
mylar.USE_NZBGET = False
mylar.USE_BLACKHOLE = False
if self.NZB_DOWNLOADER == 0:
mylar.USE_SABNZBD = True
elif self.NZB_DOWNLOADER == 1:
mylar.USE_NZBGET = True
elif self.NZB_DOWNLOADER == 2:
mylar.USE_BLACKHOLE = True
else:
#default to SABnzbd
self.NZB_DOWNLOADER = 0
mylar.USE_SABNZBD = True
if self.SAB_PRIORITY.isdigit():
if self.SAB_PRIORITY == "0": self.SAB_PRIORITY = "Default"
elif self.SAB_PRIORITY == "1": self.SAB_PRIORITY = "Low"
elif self.SAB_PRIORITY == "2": self.SAB_PRIORITY = "Normal"
elif self.SAB_PRIORITY == "3": self.SAB_PRIORITY = "High"
elif self.SAB_PRIORITY == "4": self.SAB_PRIORITY = "Paused"
else: self.SAB_PRIORITY = "Default"
if self.SAB_VERSION is not None:
config.set('SABnzbd', 'sab_version', self.SAB_VERSION)
if int(re.sub("[^0-9]", '', self.SAB_VERSION).strip()) < int(re.sub("[^0-9]", '', '0.8.0').strip()) and self.SAB_CLIENT_POST_PROCESSING is True:
logger.warn('Your SABnzbd client is less than 0.8.0, and does not support Completed Download Handling which is enabled. Disabling CDH.')
self.SAB_CLIENT_POST_PROCESSING = False
mylar.USE_WATCHDIR = False
mylar.USE_UTORRENT = False
mylar.USE_RTORRENT = False
mylar.USE_TRANSMISSION = False
mylar.USE_DELUGE = False
mylar.USE_QBITTORRENT = False
if self.TORRENT_DOWNLOADER == 0:
mylar.USE_WATCHDIR = True
elif self.TORRENT_DOWNLOADER == 1:
mylar.USE_UTORRENT = True
elif self.TORRENT_DOWNLOADER == 2:
mylar.USE_RTORRENT = True
elif self.TORRENT_DOWNLOADER == 3:
mylar.USE_TRANSMISSION = True
elif self.TORRENT_DOWNLOADER == 4:
mylar.USE_DELUGE = True
elif self.TORRENT_DOWNLOADER == 5:
mylar.USE_QBITTORRENT = True
else:
self.TORRENT_DOWNLOADER = 0
mylar.USE_WATCHDIR = True
def parse_32pfeed(self, rssfeedline):
KEYS_32P = {}
if self.ENABLE_32P and len(rssfeedline) > 1:
userid_st = rssfeedline.find('&user')
userid_en = rssfeedline.find('&', userid_st +1)
if userid_en == -1:
userid_32p = rssfeedline[userid_st +6:]
else:
userid_32p = rssfeedline[userid_st +6:userid_en]
auth_st = rssfeedline.find('&auth')
auth_en = rssfeedline.find('&', auth_st +1)
if auth_en == -1:
auth_32p = rssfeedline[auth_st +6:]
else:
auth_32p = rssfeedline[auth_st +6:auth_en]
authkey_st = rssfeedline.find('&authkey')
authkey_en = rssfeedline.find('&', authkey_st +1)
if authkey_en == -1:
authkey_32p = rssfeedline[authkey_st +9:]
else:
authkey_32p = rssfeedline[authkey_st +9:authkey_en]
KEYS_32P = {"user": userid_32p,
"auth": auth_32p,
"authkey": authkey_32p,
"passkey": self.PASSKEY_32P}
return KEYS_32P
def get_extra_newznabs(self):
extra_newznabs = zip(*[iter(self.EXTRA_NEWZNABS.split(', '))]*6)
return extra_newznabs
def get_extra_torznabs(self):
extra_torznabs = zip(*[iter(self.EXTRA_TORZNABS.split(', '))]*6)
return extra_torznabs
def provider_sequence(self):
PR = []
PR_NUM = 0
if self.ENABLE_TORRENT_SEARCH:
if self.ENABLE_32P:
PR.append('32p')
PR_NUM +=1
if self.ENABLE_PUBLIC:
PR.append('public torrents')
PR_NUM +=1
if self.NZBSU:
PR.append('nzb.su')
PR_NUM +=1
if self.DOGNZB:
PR.append('dognzb')
PR_NUM +=1
if self.EXPERIMENTAL:
PR.append('Experimental')
PR_NUM +=1
if self.ENABLE_DDL:
PR.append('DDL')
PR_NUM +=1
PPR = ['32p', 'public torrents', 'nzb.su', 'dognzb', 'Experimental', 'DDL']
if self.NEWZNAB:
for ens in self.EXTRA_NEWZNABS:
if str(ens[5]) == '1': # if newznabs are enabled
if ens[0] == "":
en_name = ens[1]
else:
en_name = ens[0]
if en_name.endswith("\""):
en_name = re.sub("\"", "", str(en_name)).strip()
PR.append(en_name)
PPR.append(en_name)
PR_NUM +=1
if self.ENABLE_TORZNAB:
for ets in self.EXTRA_TORZNABS:
if str(ets[5]) == '1': # if torznabs are enabled
if ets[0] == "":
et_name = ets[1]
else:
et_name = ets[0]
if et_name.endswith("\""):
et_name = re.sub("\"", "", str(et_name)).strip()
PR.append(et_name)
PPR.append(et_name)
PR_NUM +=1
if self.PROVIDER_ORDER is not None:
try:
PRO_ORDER = zip(*[iter(self.PROVIDER_ORDER.split(', '))]*2)
except:
PO = []
for k, v in self.PROVIDER_ORDER.iteritems():
PO.append(k)
PO.append(v)
POR = ', '.join(PO)
PRO_ORDER = zip(*[iter(POR.split(', '))]*2)
logger.fdebug(u"Original provider_order sequence: %s" % self.PROVIDER_ORDER)
#if provider order exists already, load it and then append to end any NEW entries.
logger.fdebug('Provider sequence already pre-exists. Re-loading and adding/remove any new entries')
TMPPR_NUM = 0
PROV_ORDER = []
#load original sequence
for PRO in PRO_ORDER:
PROV_ORDER.append({"order_seq": PRO[0],
"provider": str(PRO[1])})
TMPPR_NUM +=1
#calculate original sequence to current sequence for discrepancies
#print('TMPPR_NUM: %s --- PR_NUM: %s' % (TMPPR_NUM, PR_NUM))
if PR_NUM != TMPPR_NUM:
logger.fdebug('existing Order count does not match New Order count')
if PR_NUM > TMPPR_NUM:
logger.fdebug('%s New entries exist, appending to end as default ordering' % (PR_NUM - TMPPR_NUM))
TOTALPR = (TMPPR_NUM + PR_NUM)
else:
logger.fdebug('%s Disabled entries exist, removing from ordering sequence' % (TMPPR_NUM - PR_NUM))
TOTALPR = TMPPR_NUM
if PR_NUM > 0:
logger.fdebug('%s entries are enabled.' % PR_NUM)
NEW_PROV_ORDER = []
i = 0
#this should loop over ALL possible entries
while i < len(PR):
found = False
for d in PPR:
#logger.fdebug('checking entry %s against %s' % (PR[i], d) #d['provider'])
if d == PR[i]:
x = [p['order_seq'] for p in PROV_ORDER if p['provider'] == PR[i]]
if x:
ord = x[0]
else:
ord = i
found = {'provider': PR[i],
'order': ord}
break
else:
found = False
if found is not False:
new_order_seqnum = len(NEW_PROV_ORDER)
if new_order_seqnum <= found['order']:
seqnum = found['order']
else:
seqnum = new_order_seqnum
NEW_PROV_ORDER.append({"order_seq": len(NEW_PROV_ORDER),
"provider": found['provider'],
"orig_seq": int(seqnum)})
i+=1
#now we reorder based on priority of orig_seq, but use a new_order seq
xa = 0
NPROV = []
for x in sorted(NEW_PROV_ORDER, key=itemgetter('orig_seq'), reverse=False):
NPROV.append(str(xa))
NPROV.append(x['provider'])
xa+=1
PROVIDER_ORDER = NPROV
else:
#priority provider sequence in order#, ProviderName
logger.fdebug('creating provider sequence order now...')
TMPPR_NUM = 0
PROV_ORDER = []
while TMPPR_NUM < PR_NUM:
PROV_ORDER.append(str(TMPPR_NUM))
PROV_ORDER.append(PR[TMPPR_NUM])
#{"order_seq": TMPPR_NUM,
#"provider": str(PR[TMPPR_NUM])})
TMPPR_NUM +=1
PROVIDER_ORDER = PROV_ORDER
ll = ', '.join(PROVIDER_ORDER)
if not config.has_section('Providers'):
config.add_section('Providers')
config.set('Providers', 'PROVIDER_ORDER', ll)
PROVIDER_ORDER = dict(zip(*[PROVIDER_ORDER[i::2] for i in range(2)]))
setattr(self, 'PROVIDER_ORDER', PROVIDER_ORDER)
logger.fdebug('Provider Order is now set : %s ' % self.PROVIDER_ORDER)
def write_extras(self, value):
flattened = []
for item in value:
for i in item:
try:
if "\"" in i and " \"" in i:
ib = str(i).replace("\"", "").strip()
else:
ib = i
except:
ib = i
flattened.append(str(ib))
return flattened
| 58,374 | Python | .py | 1,125 | 38.787556 | 208 | 0.543779 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,224 | opds.py | evilhero_mylar/mylar/opds.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import mylar
from mylar import db, mb, importer, search, PostProcessor, versioncheck, logger, readinglist, helpers
import simplejson as simplejson
import cherrypy
from xml.sax.saxutils import escape
import os
import glob
import urllib2
from urllib import urlencode, quote_plus
import cache
import imghdr
from operator import itemgetter
from cherrypy.lib.static import serve_file, serve_download
import datetime
from mylar.webserve import serve_template
import re
cmd_list = ['root', 'Publishers', 'AllTitles', 'StoryArcs', 'ReadList', 'OneOffs', 'Comic', 'Publisher', 'Issue', 'StoryArc', 'Recent', 'deliverFile']
class OPDS(object):
def __init__(self):
self.cmd = None
self.PAGE_SIZE=mylar.CONFIG.OPDS_PAGESIZE
self.img = None
self.issue_id = None
self.file = None
self.filename = None
self.kwargs = None
self.data = None
if mylar.CONFIG.HTTP_ROOT is None:
self.opdsroot = '/opds'
elif mylar.CONFIG.HTTP_ROOT.endswith('/'):
self.opdsroot = mylar.CONFIG.HTTP_ROOT + 'opds'
else:
if mylar.CONFIG.HTTP_ROOT != '/':
self.opdsroot = mylar.CONFIG.HTTP_ROOT + '/opds'
else:
self.opdsroot = mylar.CONFIG.HTTP_ROOT + 'opds'
def checkParams(self, *args, **kwargs):
if 'cmd' not in kwargs:
self.cmd = 'root'
if not mylar.CONFIG.OPDS_ENABLE:
self.data = self._error_with_message('OPDS not enabled')
return
if not self.cmd:
if kwargs['cmd'] not in cmd_list:
self.data = self._error_with_message('Unknown command: %s' % kwargs['cmd'])
return
else:
self.cmd = kwargs.pop('cmd')
self.kwargs = kwargs
self.data = 'OK'
def fetchData(self):
if self.data == 'OK':
logger.fdebug('Recieved OPDS command: ' + self.cmd)
methodToCall = getattr(self, "_" + self.cmd)
result = methodToCall(**self.kwargs)
if self.img:
return serve_file(path=self.img, content_type='image/jpeg')
if self.file and self.filename:
if self.issue_id:
try:
readinglist.Readinglist(IssueID=self.issue_id).markasRead()
except:
logger.fdebug('No reading list found to update.')
return serve_download(path=self.file, name=self.filename)
if isinstance(self.data, basestring):
return self.data
else:
cherrypy.response.headers['Content-Type'] = "text/xml"
return serve_template(templatename="opds.html", title=self.data['title'], opds=self.data)
else:
return self.data
def _error_with_message(self, message):
error = '<feed><error>%s</error></feed>' % message
cherrypy.response.headers['Content-Type'] = "text/xml"
return error
def _dic_from_query(self, query):
myDB = db.DBConnection()
rows = myDB.select(query)
rows_as_dic = []
for row in rows:
row_as_dic = dict(zip(row.keys(), row))
rows_as_dic.append(row_as_dic)
return rows_as_dic
def _root(self, **kwargs):
myDB = db.DBConnection()
feed = {}
feed['title'] = 'Mylar OPDS'
currenturi = cherrypy.url()
feed['id'] = re.sub('/', ':', currenturi)
feed['updated'] = mylar.helpers.now()
links = []
entries=[]
links.append(getLink(href=self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='start', title='Home'))
links.append(getLink(href=self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation',rel='self'))
links.append(getLink(href='%s?cmd=search' % self.opdsroot, type='application/opensearchdescription+xml',rel='search',title='Search'))
publishers = myDB.select("SELECT ComicPublisher from comics GROUP BY ComicPublisher")
entries.append(
{
'title': 'Recent Additions',
'id': 'Recent',
'updated': mylar.helpers.now(),
'content': 'Recently Added Issues',
'href': '%s?cmd=Recent' % self.opdsroot,
'kind': 'acquisition',
'rel': 'subsection',
}
)
if len(publishers) > 0:
count = len(publishers)
entries.append(
{
'title': 'Publishers (%s)' % count,
'id': 'Publishers',
'updated': mylar.helpers.now(),
'content': 'List of Comic Publishers',
'href': '%s?cmd=Publishers' %self.opdsroot,
'kind': 'navigation',
'rel': 'subsection',
}
)
comics = mylar.helpers.havetotals()
count = 0
for comic in comics:
if comic['haveissues'] > 0:
count += 1
if count > -1:
entries.append(
{
'title': 'All Titles (%s)' % count,
'id': 'AllTitles',
'updated': mylar.helpers.now(),
'content': 'List of All Comics',
'href': '%s?cmd=AllTitles' % self.opdsroot,
'kind': 'navigation',
'rel': 'subsection',
}
)
storyArcs = mylar.helpers.listStoryArcs()
logger.debug(storyArcs)
if len(storyArcs) > 0:
entries.append(
{
'title': 'Story Arcs (%s)' % len(storyArcs),
'id': 'StoryArcs',
'updated': mylar.helpers.now(),
'content': 'List of Story Arcs',
'href': '%s?cmd=StoryArcs' % self.opdsroot,
'kind': 'navigation',
'rel': 'subsection',
}
)
readList = myDB.select("SELECT * from readlist")
if len(readList) > 0:
entries.append(
{
'title': 'Read List (%s)' % len(readList),
'id': 'ReadList',
'updated': mylar.helpers.now(),
'content': 'Current Read List',
'href': '%s?cmd=ReadList' % self.opdsroot,
'kind': 'navigation',
'rel': 'subsection',
}
)
gbd = mylar.CONFIG.GRABBAG_DIR + '/*'
oneofflist = glob.glob(gbd)
if len(oneofflist) > 0:
entries.append(
{
'title': 'One-Offs (%s)' % len(oneofflist),
'id': 'OneOffs',
'updated': mylar.helpers.now(),
'content': 'OneOffs',
'href': '%s?cmd=OneOffs' % self.opdsroot,
'kind': 'navigation',
'rel': 'subsection',
}
)
feed['links'] = links
feed['entries'] = entries
self.data = feed
return
def _Publishers(self, **kwargs):
index = 0
if 'index' in kwargs:
index = int(kwargs['index'])
myDB = db.DBConnection()
feed = {}
feed['title'] = 'Mylar OPDS - Publishers'
feed['id'] = 'Publishers'
feed['updated'] = mylar.helpers.now()
links = []
entries=[]
links.append(getLink(href=self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='start', title='Home'))
links.append(getLink(href='%s?cmd=Publishers' % self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation',rel='self'))
publishers = myDB.select("SELECT ComicPublisher from comics GROUP BY ComicPublisher")
comics = mylar.helpers.havetotals()
for publisher in publishers:
lastupdated = '0000-00-00'
totaltitles = 0
for comic in comics:
if comic['ComicPublisher'] == publisher['ComicPublisher'] and comic['haveissues'] > 0:
totaltitles += 1
if comic['DateAdded'] > lastupdated:
lastupdated = comic['DateAdded']
if totaltitles > 0:
entries.append(
{
'title': escape('%s (%s)' % (publisher['ComicPublisher'], totaltitles)),
'id': escape('publisher:%s' % publisher['ComicPublisher']),
'updated': lastupdated,
'content': escape('%s (%s)' % (publisher['ComicPublisher'], totaltitles)),
'href': '%s?cmd=Publisher&pubid=%s' % (self.opdsroot, quote_plus(publisher['ComicPublisher'])),
'kind': 'navigation',
'rel': 'subsection',
}
)
if len(entries) > (index + self.PAGE_SIZE):
links.append(
getLink(href='%s?cmd=AllTitles&index=%s' % (self.opdsroot, index+self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='next'))
if index >= self.PAGE_SIZE:
links.append(
getLink(href='%s?cmd=AllTitles&index=%s' % (self.opdsroot, index-self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='previous'))
feed['links'] = links
feed['entries'] = entries[index:(index+self.PAGE_SIZE)]
self.data = feed
return
def _AllTitles(self, **kwargs):
index = 0
if 'index' in kwargs:
index = int(kwargs['index'])
myDB = db.DBConnection()
feed = {}
feed['title'] = 'Mylar OPDS - All Titles'
feed['id'] = 'AllTitles'
feed['updated'] = mylar.helpers.now()
links = []
entries=[]
links.append(getLink(href=self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='start', title='Home'))
links.append(getLink(href='%s?cmd=AllTitles' % self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation',rel='self'))
comics = mylar.helpers.havetotals()
for comic in comics:
if comic['haveissues'] > 0:
entries.append(
{
'title': escape('%s (%s) (comicID: %s)' % (comic['ComicName'], comic['ComicYear'], comic['ComicID'])),
'id': escape('comic:%s (%s) [%s]' % (comic['ComicName'], comic['ComicYear'], comic['ComicID'])),
'updated': comic['DateAdded'],
'content': escape('%s (%s)' % (comic['ComicName'], comic['ComicYear'])),
'href': '%s?cmd=Comic&comicid=%s' % (self.opdsroot, quote_plus(comic['ComicID'])),
'kind': 'acquisition',
'rel': 'subsection',
}
)
if len(entries) > (index + self.PAGE_SIZE):
links.append(
getLink(href='%s?cmd=AllTitles&index=%s' % (self.opdsroot, index+self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='next'))
if index >= self.PAGE_SIZE:
links.append(
getLink(href='%s?cmd=AllTitles&index=%s' % (self.opdsroot, index-self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='previous'))
feed['links'] = links
feed['entries'] = entries[index:(index+self.PAGE_SIZE)]
self.data = feed
return
def _Publisher(self, **kwargs):
index = 0
if 'index' in kwargs:
index = int(kwargs['index'])
myDB = db.DBConnection()
if 'pubid' not in kwargs:
self.data =self._error_with_message('No Publisher Provided')
return
links = []
entries=[]
allcomics = mylar.helpers.havetotals()
for comic in allcomics:
if comic['ComicPublisher'] == kwargs['pubid'] and comic['haveissues'] > 0:
entries.append(
{
'title': escape('%s (%s)' % (comic['ComicName'], comic['ComicYear'])),
'id': escape('comic:%s (%s)' % (comic['ComicName'], comic['ComicYear'])),
'updated': comic['DateAdded'],
'content': escape('%s (%s)' % (comic['ComicName'], comic['ComicYear'])),
'href': '%s?cmd=Comic&comicid=%s' % (self.opdsroot, quote_plus(comic['ComicID'])),
'kind': 'acquisition',
'rel': 'subsection',
}
)
feed = {}
pubname = '%s (%s)' % (escape(kwargs['pubid']),len(entries))
feed['title'] = 'Mylar OPDS - %s' % (pubname)
feed['id'] = 'publisher:%s' % escape(kwargs['pubid'])
feed['updated'] = mylar.helpers.now()
links.append(getLink(href=self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='start', title='Home'))
links.append(getLink(href='%s?cmd=Publishers' % self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation',rel='self'))
if len(entries) > (index + self.PAGE_SIZE):
links.append(
getLink(href='%s?cmd=Publisher&pubid=%s&index=%s' % (self.opdsroot, quote_plus(kwargs['pubid']),index+self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='next'))
if index >= self.PAGE_SIZE:
links.append(
getLink(href='%s?cmd=Publisher&pubid=%s&index=%s' % (self.opdsroot, quote_plus(kwargs['pubid']),index-self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='previous'))
feed['links'] = links
feed['entries'] = entries[index:(index+self.PAGE_SIZE)]
self.data = feed
return
def _Comic(self, **kwargs):
index = 0
if 'index' in kwargs:
index = int(kwargs['index'])
myDB = db.DBConnection()
if 'comicid' not in kwargs:
self.data =self._error_with_message('No ComicID Provided')
return
links = []
entries=[]
comic = myDB.selectone('SELECT * from comics where ComicID=?', (kwargs['comicid'],)).fetchone()
if not comic:
self.data = self._error_with_message('Comic Not Found')
return
issues = self._dic_from_query('SELECT * from issues WHERE ComicID="' + kwargs['comicid'] + '"order by Int_IssueNumber DESC')
if mylar.CONFIG.ANNUALS_ON:
annuals = self._dic_from_query('SELECT * FROM annuals WHERE ComicID="' + kwargs['comicid'] + '"')
else:
annuals = []
for annual in annuals:
issues.append(annual)
issues = [x for x in issues if x['Location']]
if index <= len(issues):
subset = issues[index:(index+self.PAGE_SIZE)]
for issue in subset:
if 'DateAdded' in issue and issue['DateAdded']:
updated = issue['DateAdded']
else:
updated = issue['ReleaseDate']
image = None
thumbnail = None
if not 'ReleaseComicID' in issue:
title = escape('%s (%s) #%s - %s' % (issue['ComicName'], comic['ComicYear'], issue['Issue_Number'], issue['IssueName']))
image = issue['ImageURL_ALT']
thumbnail = issue['ImageURL']
else:
title = escape('Annual %s - %s' % (issue['Issue_Number'], issue['IssueName']))
fileloc = os.path.join(comic['ComicLocation'],issue['Location'])
if not os.path.isfile(fileloc):
logger.debug("Missing File: %s" % (fileloc))
continue
metainfo = None
if mylar.CONFIG.OPDS_METAINFO:
metainfo = mylar.helpers.IssueDetails(fileloc)
if not metainfo:
metainfo = [{'writer': None,'summary': ''}]
entries.append(
{
'title': escape(title),
'id': escape('comic:%s (%s) [%s] - %s' % (issue['ComicName'], comic['ComicYear'], comic['ComicID'], issue['Issue_Number'])),
'updated': updated,
'content': escape('%s' % (metainfo[0]['summary'])),
'href': '%s?cmd=Issue&issueid=%s&file=%s' % (self.opdsroot, quote_plus(issue['IssueID']),quote_plus(issue['Location'].encode('utf-8'))),
'kind': 'acquisition',
'rel': 'file',
'author': metainfo[0]['writer'],
'image': image,
'thumbnail': thumbnail,
}
)
feed = {}
comicname = '%s' % (escape(comic['ComicName']))
feed['title'] = 'Mylar OPDS - %s' % (comicname)
feed['id'] = escape('comic:%s (%s)' % (comic['ComicName'], comic['ComicYear']))
feed['updated'] = comic['DateAdded']
links.append(getLink(href=self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='start', title='Home'))
links.append(getLink(href='%s?cmd=Comic&comicid=%s' % (self.opdsroot, quote_plus(kwargs['comicid'])),type='application/atom+xml; profile=opds-catalog; kind=navigation',rel='self'))
if len(issues) > (index + self.PAGE_SIZE):
links.append(
getLink(href='%s?cmd=Comic&comicid=%s&index=%s' % (self.opdsroot, quote_plus(kwargs['comicid']),index+self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='next'))
if index >= self.PAGE_SIZE:
links.append(
getLink(href='%s?cmd=Comic&comicid=%s&index=%s' % (self.opdsroot, quote_plus(kwargs['comicid']),index-self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='previous'))
feed['links'] = links
feed['entries'] = entries
self.data = feed
return
def _Recent(self, **kwargs):
index = 0
if 'index' in kwargs:
index = int(kwargs['index'])
myDB = db.DBConnection()
links = []
entries=[]
recents = self._dic_from_query('SELECT * from snatched WHERE Status = "Post-Processed" OR Status = "Downloaded" order by DateAdded DESC LIMIT 120')
if index <= len(recents):
number = 1
subset = recents[index:(index+self.PAGE_SIZE)]
for issue in subset:
issuebook = myDB.fetch('SELECT * from issues WHERE IssueID = ?', (issue['IssueID'],)).fetchone()
if not issuebook:
issuebook = myDB.fetch('SELECT * from annuals WHERE IssueID = ?', (issue['IssueID'],)).fetchone()
comic = myDB.fetch('SELECT * from comics WHERE ComicID = ?', (issue['ComicID'],)).fetchone()
updated = issue['DateAdded']
image = None
thumbnail = None
if issuebook:
if not 'ReleaseComicID' in issuebook.keys():
if issuebook['DateAdded'] is None:
title = escape('%03d: %s #%s - %s (In stores %s)' % (index + number, issuebook['ComicName'], issuebook['Issue_Number'], issuebook['IssueName'], issuebook['ReleaseDate']))
image = issuebook['ImageURL_ALT']
thumbnail = issuebook['ImageURL']
else:
title = escape('%03d: %s #%s - %s (Added to Mylar %s, in stores %s)' % (index + number, issuebook['ComicName'], issuebook['Issue_Number'], issuebook['IssueName'], issuebook['DateAdded'], issuebook['ReleaseDate']))
image = issuebook['ImageURL_ALT']
thumbnail = issuebook['ImageURL']
else:
title = escape('%03d: %s Annual %s - %s (In stores %s)' % (index + number, issuebook['ComicName'], issuebook['Issue_Number'], issuebook['IssueName'], issuebook['ReleaseDate']))
# logger.info("%s - %s" % (comic['ComicLocation'], issuebook['Location']))
number +=1
if not issuebook['Location']:
continue
location = issuebook['Location'].encode('utf-8')
fileloc = os.path.join(comic['ComicLocation'],issuebook['Location'])
metainfo = None
if mylar.CONFIG.OPDS_METAINFO:
metainfo = mylar.helpers.IssueDetails(fileloc)
if not metainfo:
metainfo = [{'writer': None,'summary': ''}]
entries.append(
{
'title': title,
'id': escape('comic:%s (%s) - %s' % (issuebook['ComicName'], comic['ComicYear'], issuebook['Issue_Number'])),
'updated': updated,
'content': escape('%s' % (metainfo[0]['summary'])),
'href': '%s?cmd=Issue&issueid=%s&file=%s' % (self.opdsroot, quote_plus(issuebook['IssueID']),quote_plus(location)),
'kind': 'acquisition',
'rel': 'file',
'author': metainfo[0]['writer'],
'image': image,
'thumbnail': thumbnail,
}
)
feed = {}
feed['title'] = 'Mylar OPDS - New Arrivals'
feed['id'] = escape('New Arrivals')
feed['updated'] = mylar.helpers.now()
links.append(getLink(href=self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='start', title='Home'))
links.append(getLink(href='%s?cmd=Recent' % (self.opdsroot),type='application/atom+xml; profile=opds-catalog; kind=navigation',rel='self'))
if len(recents) > (index + self.PAGE_SIZE):
links.append(
getLink(href='%s?cmd=Recent&index=%s' % (self.opdsroot,index+self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='next'))
if index >= self.PAGE_SIZE:
links.append(
getLink(href='%s?cmd=Recent&index=%s' % (self.opdsroot,index-self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='previous'))
feed['links'] = links
feed['entries'] = entries
self.data = feed
return
def _deliverFile(self, **kwargs):
logger.fdebug("_deliverFile: kwargs: %s" % kwargs)
if 'file' not in kwargs:
self.data = self._error_with_message('No file provided')
elif 'filename' not in kwargs:
self.data = self._error_with_message('No filename provided')
else:
#logger.fdebug("file name: %s" % str(kwargs['file'])
self.filename = os.path.split(str(kwargs['file']))[1]
self.file = str(kwargs['file'])
return
def _Issue(self, **kwargs):
if 'issueid' not in kwargs:
self.data = self._error_with_message('No ComicID Provided')
return
myDB = db.DBConnection()
issuetype = 0
issue = myDB.selectone("SELECT * from storyarcs WHERE IssueID=? and Location IS NOT NULL",
(kwargs['issueid'],)).fetchone()
if not issue:
issue = myDB.selectone("SELECT * from issues WHERE IssueID=?", (kwargs['issueid'],)).fetchone()
if not issue:
issue = myDB.selectone("SELECT * from annuals WHERE IssueID=?", (kwargs['issueid'],)).fetchone()
if not issue:
self.data = self._error_with_message('Issue Not Found')
return
comic = myDB.selectone("SELECT * from comics WHERE ComicID=?", (issue['ComicID'],)).fetchone()
if not comic:
self.data = self._error_with_message('Comic Not Found in Watchlist')
return
self.issue_id = issue['IssueID']
self.file = os.path.join(comic['ComicLocation'],issue['Location'])
self.filename = issue['Location']
else:
self.issue_id = issue['IssueID']
self.file = issue['Location']
self.filename = os.path.split(issue['Location'])[1]
return
def _StoryArcs(self, **kwargs):
index = 0
if 'index' in kwargs:
index = int(kwargs['index'])
myDB = db.DBConnection()
links = []
entries=[]
arcs = []
storyArcs = mylar.helpers.listStoryArcs()
for arc in storyArcs:
issuecount = 0
arcname = ''
updated = '0000-00-00'
arclist = myDB.select("SELECT * from storyarcs WHERE StoryArcID=?", (arc,))
for issue in arclist:
if issue['Status'] == 'Downloaded':
issuecount += 1
arcname = issue['StoryArc']
if issue['IssueDate'] > updated:
updated = issue['IssueDate']
if issuecount > 0:
arcs.append({'StoryArcName': arcname, 'StoryArcID': arc, 'IssueCount': issuecount, 'updated': updated})
newlist = sorted(arcs, key=itemgetter('StoryArcName'))
subset = newlist[index:(index + self.PAGE_SIZE)]
for arc in subset:
entries.append(
{
'title': '%s (%s)' % (arc['StoryArcName'],arc['IssueCount']),
'id': escape('storyarc:%s' % (arc['StoryArcID'])),
'updated': arc['updated'],
'content': '%s (%s)' % (arc['StoryArcName'],arc['IssueCount']),
'href': '%s?cmd=StoryArc&arcid=%s' % (self.opdsroot, quote_plus(arc['StoryArcID'])),
'kind': 'acquisition',
'rel': 'subsection',
}
)
feed = {}
feed['title'] = 'Mylar OPDS - Story Arcs'
feed['id'] = 'StoryArcs'
feed['updated'] = mylar.helpers.now()
links.append(getLink(href=self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='start', title='Home'))
links.append(getLink(href='%s?cmd=StoryArcs' % self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation',rel='self'))
if len(arcs) > (index + self.PAGE_SIZE):
links.append(
getLink(href='%s?cmd=StoryArcs&index=%s' % (self.opdsroot, index+self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='next'))
if index >= self.PAGE_SIZE:
links.append(
getLink(href='%s?cmd=StoryArcs&index=%s' % (self.opdsroot, index-self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='previous'))
feed['links'] = links
feed['entries'] = entries
self.data = feed
return
def _OneOffs(self, **kwargs):
index = 0
if 'index' in kwargs:
index = int(kwargs['index'])
links = []
entries = []
flist = []
book = ''
gbd = str(mylar.CONFIG.GRABBAG_DIR + '/*').encode('utf-8')
flist = glob.glob(gbd)
readlist = []
for book in flist:
issue = {}
fileexists = True
book = book.encode('utf-8')
issue['Title'] = book
issue['IssueID'] = book
issue['fileloc'] = book
issue['filename'] = book
issue['image'] = None
issue['thumbnail'] = None
issue['updated'] = helpers.now()
if not os.path.isfile(issue['fileloc']):
fileexists = False
if fileexists:
readlist.append(issue)
if len(readlist) > 0:
if index <= len(readlist):
subset = readlist[index:(index + self.PAGE_SIZE)]
for issue in subset:
metainfo = None
metainfo = [{'writer': None,'summary': ''}]
entries.append(
{
'title': escape(issue['Title']),
'id': escape('comic:%s' % issue['IssueID']),
'updated': issue['updated'],
'content': escape('%s' % (metainfo[0]['summary'])),
'href': '%s?cmd=deliverFile&file=%s&filename=%s' % (self.opdsroot, quote_plus(issue['fileloc']), quote_plus(issue['filename'])),
'kind': 'acquisition',
'rel': 'file',
'author': metainfo[0]['writer'],
'image': issue['image'],
'thumbnail': issue['thumbnail'],
}
)
feed = {}
feed['title'] = 'Mylar OPDS - One-Offs'
feed['id'] = escape('OneOffs')
feed['updated'] = mylar.helpers.now()
links.append(getLink(href=self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='start', title='Home'))
links.append(getLink(href='%s?cmd=OneOffs' % self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation',rel='self'))
if len(readlist) > (index + self.PAGE_SIZE):
links.append(
getLink(href='%s?cmd=OneOffs&index=%s' % (self.opdsroot, index+self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='next'))
if index >= self.PAGE_SIZE:
links.append(
getLink(href='%s?cmd=Read&index=%s' % (self.opdsroot, index-self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='previous'))
feed['links'] = links
feed['entries'] = entries
self.data = feed
return
def _ReadList(self, **kwargs):
index = 0
if 'index' in kwargs:
index = int(kwargs['index'])
myDB = db.DBConnection()
links = []
entries = []
rlist = self._dic_from_query("SELECT * from readlist where status!='Read'")
readlist = []
for book in rlist:
fileexists = False
issue = {}
issue['Title'] = '%s #%s' % (book['ComicName'], book['Issue_Number'])
issue['IssueID'] = book['IssueID']
comic = myDB.selectone("SELECT * from comics WHERE ComicID=?", (book['ComicID'],)).fetchone()
bookentry = myDB.selectone("SELECT * from issues WHERE IssueID=?", (book['IssueID'],)).fetchone()
if bookentry:
if bookentry['Location']:
fileexists = True
issue['fileloc'] = os.path.join(comic['ComicLocation'], bookentry['Location'])
issue['filename'] = bookentry['Location'].encode('utf-8')
issue['image'] = bookentry['ImageURL_ALT']
issue['thumbnail'] = bookentry['ImageURL']
if bookentry['DateAdded']:
issue['updated'] = bookentry['DateAdded']
else:
issue['updated'] = bookentry['IssueDate']
else:
annualentry = myDB.selectone("SELECT * from annuals WHERE IssueID=?", (book['IssueID'],)).fetchone()
if annualentry:
if annualentry['Location']:
fileexists = True
issue['fileloc'] = os.path.join(comic['ComicLocation'], annualentry['Location'])
issue['filename'] = annualentry['Location'].encode('utf-8')
issue['image'] = None
issue['thumbnail'] = None
issue['updated'] = annualentry['IssueDate']
if not os.path.isfile(issue['fileloc']):
fileexists = False
if fileexists:
readlist.append(issue)
if len(readlist) > 0:
if index <= len(readlist):
subset = readlist[index:(index + self.PAGE_SIZE)]
for issue in subset:
metainfo = None
if mylar.CONFIG.OPDS_METAINFO:
metainfo = mylar.helpers.IssueDetails(issue['fileloc'])
if not metainfo:
metainfo = [{'writer': None,'summary': ''}]
entries.append(
{
'title': escape(issue['Title']),
'id': escape('comic:%s' % issue['IssueID']),
'updated': issue['updated'],
'content': escape('%s' % (metainfo[0]['summary'])),
'href': '%s?cmd=Issue&issueid=%s&file=%s' % (self.opdsroot, quote_plus(issue['IssueID']),quote_plus(issue['filename'])),
'kind': 'acquisition',
'rel': 'file',
'author': metainfo[0]['writer'],
'image': issue['image'],
'thumbnail': issue['thumbnail'],
}
)
feed = {}
feed['title'] = 'Mylar OPDS - ReadList'
feed['id'] = escape('ReadList')
feed['updated'] = mylar.helpers.now()
links.append(getLink(href=self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='start', title='Home'))
links.append(getLink(href='%s?cmd=ReadList' % self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation',rel='self'))
if len(readlist) > (index + self.PAGE_SIZE):
links.append(
getLink(href='%s?cmd=ReadList&index=%s' % (self.opdsroot, index+self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='next'))
if index >= self.PAGE_SIZE:
links.append(
getLink(href='%s?cmd=Read&index=%s' % (self.opdsroot, index-self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='previous'))
feed['links'] = links
feed['entries'] = entries
self.data = feed
return
def _StoryArc(self, **kwargs):
index = 0
if 'index' in kwargs:
index = int(kwargs['index'])
myDB = db.DBConnection()
if 'arcid' not in kwargs:
self.data =self._error_with_message('No ArcID Provided')
return
links = []
entries=[]
arclist = self._dic_from_query("SELECT * from storyarcs WHERE StoryArcID='" + kwargs['arcid'] + "' ORDER BY ReadingOrder")
newarclist = []
arcname = ''
for book in arclist:
arcname = book['StoryArc']
fileexists = False
issue = {}
issue['ReadingOrder'] = book['ReadingOrder']
issue['Title'] = '%s #%s' % (book['ComicName'],book['IssueNumber'])
issue['IssueID'] = book['IssueID']
issue['fileloc'] = ''
if book['Location']:
issue['fileloc'] = book['Location']
fileexists = True
issue['filename'] = os.path.split(book['Location'])[1].encode('utf-8')
issue['image'] = None
issue['thumbnail'] = None
issue['updated'] = book['IssueDate']
else:
bookentry = myDB.selectone("SELECT * from issues WHERE IssueID=?", (book['IssueID'],)).fetchone()
if bookentry:
if bookentry['Location']:
comic = myDB.selectone("SELECT * from comics WHERE ComicID=?", ( bookentry['ComicID'],)).fetchone()
fileexists = True
issue['fileloc'] = os.path.join(comic['ComicLocation'], bookentry['Location'])
issue['filename'] = bookentry['Location'].encode('utf-8')
issue['image'] = bookentry['ImageURL_ALT']
issue['thumbnail'] = bookentry['ImageURL']
if bookentry['DateAdded']:
issue['updated'] = bookentry['DateAdded']
else:
issue['updated'] = bookentry['IssueDate']
else:
annualentry = myDB.selectone("SELECT * from annuals WHERE IssueID=?", (book['IssueID'],)).fetchone()
if annualentry:
if annualentry['Location']:
comic = myDB.selectone("SELECT * from comics WHERE ComicID=?", ( annualentry['ComicID'],))
fileexists = True
issue['fileloc'] = os.path.join(comic['ComicLocation'], annualentry['Location'])
issue['filename'] = annualentry['Location'].encode('utf-8')
issue['image'] = None
issue['thumbnail'] = None
issue['updated'] = annualentry['IssueDate']
else:
if book['Location']:
fileexists = True
issue['fileloc'] = book['Location']
issue['filename'] = os.path.split(book['Location'])[1].encode('utf-8')
issue['image'] = None
issue['thumbnail'] = None
issue['updated'] = book['IssueDate']
if not os.path.isfile(issue['fileloc']):
fileexists = False
if fileexists:
newarclist.append(issue)
if len(newarclist) > 0:
if index <= len(newarclist):
subset = newarclist[index:(index + self.PAGE_SIZE)]
for issue in subset:
metainfo = None
if mylar.CONFIG.OPDS_METAINFO:
metainfo = mylar.helpers.IssueDetails(issue['fileloc'])
if not metainfo:
metainfo = [{'writer': None,'summary': ''}]
entries.append(
{
'title': escape('%s - %s' % (issue['ReadingOrder'], issue['Title'])),
'id': escape('comic:%s' % issue['IssueID']),
'updated': issue['updated'],
'content': escape('%s' % (metainfo[0]['summary'])),
'href': '%s?cmd=Issue&issueid=%s&file=%s' % (self.opdsroot, quote_plus(issue['IssueID']),quote_plus(issue['filename'])),
'kind': 'acquisition',
'rel': 'file',
'author': metainfo[0]['writer'],
'image': issue['image'],
'thumbnail': issue['thumbnail'],
}
)
feed = {}
feed['title'] = 'Mylar OPDS - %s' % escape(arcname)
feed['id'] = escape('storyarc:%s' % kwargs['arcid'])
feed['updated'] = mylar.helpers.now()
links.append(getLink(href=self.opdsroot,type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='start', title='Home'))
links.append(getLink(href='%s?cmd=StoryArc&arcid=%s' % (self.opdsroot, quote_plus(kwargs['arcid'])),type='application/atom+xml; profile=opds-catalog; kind=navigation',rel='self'))
if len(newarclist) > (index + self.PAGE_SIZE):
links.append(
getLink(href='%s?cmd=StoryArc&arcid=%s&index=%s' % (self.opdsroot, quote_plus(kwargs['arcid']),index+self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='next'))
if index >= self.PAGE_SIZE:
links.append(
getLink(href='%s?cmd=StoryArc&arcid=%s&index=%s' % (self.opdsroot, quote_plus(kwargs['arcid']),index-self.PAGE_SIZE), type='application/atom+xml; profile=opds-catalog; kind=navigation', rel='previous'))
feed['links'] = links
feed['entries'] = entries
self.data = feed
return
def getLink(href=None, type=None, rel=None, title=None):
link = {}
if href:
link['href'] = href
if type:
link['type'] = type
if rel:
link['rel'] = rel
if title:
link['title'] = title
return link
| 42,217 | Python | .py | 817 | 36.671971 | 241 | 0.520231 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,225 | getcomics.py | evilhero_mylar/mylar/getcomics.py | # -*- coding: utf-8 -*-
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from StringIO import StringIO
import urllib
from threading import Thread
import os
import sys
import re
import gzip
import time
import datetime
import json
from bs4 import BeautifulSoup
import requests
import cfscrape
import zipfile
import logger
import mylar
from mylar import db
class GC(object):
def __init__(self, query=None, issueid=None, comicid=None, oneoff=False):
self.valreturn = []
self.url = 'https://getcomics.info'
self.query = query
self.comicid = comicid
self.issueid = issueid
self.oneoff = oneoff
self.local_filename = os.path.join(mylar.CONFIG.CACHE_DIR, "getcomics.html")
self.headers = {'Accept-encoding': 'gzip', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1', 'Referer': 'https://getcomics.info/'}
def search(self):
with cfscrape.create_scraper() as s:
cf_cookievalue, cf_user_agent = s.get_tokens(self.url, headers=self.headers)
t = s.get(self.url+'/', params={'s': self.query}, verify=True, cookies=cf_cookievalue, headers=self.headers, stream=True, timeout=30)
with open(self.local_filename, 'wb') as f:
for chunk in t.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
return self.search_results()
def loadsite(self, id, link):
title = os.path.join(mylar.CONFIG.CACHE_DIR, 'getcomics-' + id)
with cfscrape.create_scraper() as s:
self.cf_cookievalue, cf_user_agent = s.get_tokens(link, headers=self.headers)
t = s.get(link, verify=True, cookies=self.cf_cookievalue, headers=self.headers, stream=True, timeout=30)
with open(title+'.html', 'wb') as f:
for chunk in t.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
def search_results(self):
results = {}
resultlist = []
soup = BeautifulSoup(open(self.local_filename), 'html.parser')
resultline = soup.find("span", {"class": "cover-article-count"}).get_text(strip=True)
logger.info('There are %s results' % re.sub('Articles', '', resultline).strip())
for f in soup.findAll("article"):
id = f['id']
lk = f.find('a')
link = lk['href']
titlefind = f.find("h1", {"class": "post-title"})
title = titlefind.get_text(strip=True)
title = re.sub(u'\u2013', '-', title).strip()
filename = title
issues = None
pack = False
#see if it's a pack type
issfind_st = title.find('#')
issfind_en = title.find('-', issfind_st)
if issfind_en != -1:
if all([title[issfind_en+1] == ' ', title[issfind_en+2].isdigit()]):
iss_en = title.find(' ', issfind_en+2)
if iss_en != -1:
issues = title[issfind_st+1:iss_en]
pack = True
if title[issfind_en+1].isdigit():
iss_en = title.find(' ', issfind_en+1)
if iss_en != -1:
issues = title[issfind_st+1:iss_en]
pack = True
# if it's a pack - remove the issue-range and the possible issue years (cause it most likely will span) and pass thru as separate items
if pack is True:
title = re.sub(issues, '', title).strip()
if title.endswith('#'):
title = title[:-1].strip()
else:
if any(['Marvel Week+' in title, 'INDIE Week+' in title, 'Image Week' in title, 'DC Week+' in title]):
continue
option_find = f.find("p", {"style": "text-align: center;"})
i = 0
while (i <= 2 and option_find is not None):
option_find = option_find.findNext(text=True)
if 'Year' in option_find:
year = option_find.findNext(text=True)
year = re.sub('\|', '', year).strip()
if pack is True and '-' in year:
title = re.sub('\('+year+'\)', '', title).strip()
else:
size = option_find.findNext(text=True)
if all([re.sub(':', '', size).strip() != 'Size', len(re.sub('[^0-9]', '', size).strip()) > 0]):
if 'MB' in size:
size = re.sub('MB', 'M', size).strip()
elif 'GB' in size:
size = re.sub('GB', 'G', size).strip()
if '//' in size:
nwsize = size.find('//')
size = re.sub('\[', '', size[:nwsize]).strip()
else:
size = '0M'
i+=1
dateline = f.find('time')
datefull = dateline['datetime']
datestamp = time.mktime(time.strptime(datefull, "%Y-%m-%d"))
resultlist.append({"title": title,
"pubdate": datetime.datetime.fromtimestamp(float(datestamp)).strftime('%a, %d %b %Y %H:%M:%S'),
"filename": filename,
"size": re.sub(' ', '', size).strip(),
"pack": pack,
"issues": issues,
"link": link,
"year": year,
"id": re.sub('post-', '', id).strip(),
"site": 'DDL'})
logger.fdebug('%s [%s]' % (title, size))
results['entries'] = resultlist
return results
def parse_downloadresults(self, id, mainlink):
myDB = db.DBConnection()
series = None
year = None
size = None
title = os.path.join(mylar.CONFIG.CACHE_DIR, 'getcomics-' + id)
soup = BeautifulSoup(open(title+'.html'), 'html.parser')
orig_find = soup.find("p", {"style": "text-align: center;"})
i = 0
option_find = orig_find
possible_more = None
while True: #i <= 10:
prev_option = option_find
option_find = option_find.findNext(text=True)
if i == 0 and series is None:
series = option_find
elif 'Year' in option_find:
year = option_find.findNext(text=True)
year = re.sub('\|', '', year).strip()
else:
if 'Size' in prev_option:
size = option_find #.findNext(text=True)
possible_more = orig_find.next_sibling
break
i+=1
logger.fdebug('Now downloading: %s [%s] / %s ... this can take a while (go get some take-out)...' % (series, year, size))
link = None
for f in soup.findAll("div", {"class": "aio-pulse"}):
lk = f.find('a')
if lk['title'] == 'Download Now':
link = {"series": series,
"site": lk['title'],
"year": year,
"issues": None,
"size": size,
"link": lk['href']}
break #get the first link just to test
links = []
if link is None and possible_more.name == 'ul':
try:
bb = possible_more.findAll('li')
except:
pass
else:
for x in bb:
linkline = x.find('a')
if linkline:
if 'go.php' in linkline['href']:
volume = x.findNext(text=True)
if u'\u2013' in volume:
volume = re.sub(u'\u2013', '-', volume)
#volume label contains series, issue(s), year(s), and size
series_st = volume.find('(')
issues_st = volume.find('#')
series = volume[:series_st]
if any([issues_st == -1, series_st == -1]):
issues = None
else:
series = volume[:issues_st].strip()
issues = volume[issues_st+1:series_st].strip()
year_end = volume.find(')', series_st+1)
year = re.sub('[\(\)]', '', volume[series_st+1: year_end]).strip()
size_end = volume.find(')', year_end+1)
size = re.sub('[\(\)]', '', volume[year_end+1: size_end]).strip()
linked = linkline['href']
site = linkline.findNext(text=True)
if site == 'Main Server':
links.append({"series": series,
"site": site,
"year": year,
"issues": issues,
"size": size,
"link": linked})
else:
check_extras = soup.findAll("h3")
for sb in check_extras:
header = sb.findNext(text=True)
if header == 'TPBs':
nxt = sb.next_sibling
if nxt.name == 'ul':
bb = nxt.findAll('li')
for x in bb:
volume = x.findNext(text=True)
if u'\u2013' in volume:
volume = re.sub(u'\u2013', '-', volume)
series_st = volume.find('(')
issues_st = volume.find('#')
series = volume[:issues_st].strip()
issues = volume[issues_st:series_st].strip()
year_end = volume.find(')', series_st+1)
year = re.sub('[\(\)\|]', '', volume[series_st+1: year_end]).strip()
size_end = volume.find(')', year_end+1)
size = re.sub('[\(\)\|]', '', volume[year_end+1: size_end]).strip()
linkline = x.find('a')
linked = linkline['href']
site = linkline.findNext(text=True)
links.append({"series": series,
"volume": volume,
"site": site,
"year": year,
"issues": issues,
"size": size,
"link": linked})
if all([link is None, len(links) == 0]):
logger.warn('Unable to retrieve any valid immediate download links. They might not exist.')
return {'success': False}
if all([link is not None, len(links) == 0]):
logger.info('only one item discovered, changing queue length to accomodate: %s [%s]' % (link, type(link)))
links = [link]
elif len(links) > 0:
if link is not None:
links.append(link)
logger.fdebug('[DDL-QUEUE] Making sure we download the original item in addition to the extra packs.')
if len(links) > 1:
logger.fdebug('[DDL-QUEUER] This pack has been broken up into %s separate packs - queueing each in sequence for your enjoyment.' % len(links))
cnt = 1
for x in links:
if len(links) == 1:
mod_id = id
else:
mod_id = id+'-'+str(cnt)
#logger.fdebug('[%s] %s (%s) %s [%s][%s]' % (x['site'], x['series'], x['year'], x['issues'], x['size'], x['link']))
ctrlval = {'id': mod_id}
vals = {'series': x['series'],
'year': x['year'],
'size': x['size'],
'issues': x['issues'],
'issueid': self.issueid,
'comicid': self.comicid,
'link': x['link'],
'mainlink': mainlink,
'updated_date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
'status': 'Queued'}
myDB.upsert('ddl_info', vals, ctrlval)
mylar.DDL_QUEUE.put({'link': x['link'],
'mainlink': mainlink,
'series': x['series'],
'year': x['year'],
'size': x['size'],
'comicid': self.comicid,
'issueid': self.issueid,
'oneoff': self.oneoff,
'id': mod_id,
'resume': None})
cnt+=1
return {'success': True}
def downloadit(self, id, link, mainlink, resume=None):
#logger.info('[%s] %s -- mainlink: %s' % (id, link, mainlink))
if mylar.DDL_LOCK is True:
logger.fdebug('[DDL] Another item is currently downloading via DDL. Only one item can be downloaded at a time using DDL. Patience.')
return
else:
mylar.DDL_LOCK = True
myDB = db.DBConnection()
filename = None
try:
with cfscrape.create_scraper() as s:
if resume is not None:
logger.info('[DDL-RESUME] Attempting to resume from: %s bytes' % resume)
self.headers['Range'] = 'bytes=%d-' % resume
cf_cookievalue, cf_user_agent = s.get_tokens(mainlink, headers=self.headers, timeout=30)
t = s.get(link, verify=True, cookies=cf_cookievalue, headers=self.headers, stream=True, timeout=30)
filename = os.path.basename(urllib.unquote(t.url).decode('utf-8'))
if 'GetComics.INFO' in filename:
filename = re.sub('GetComics.INFO', '', filename, re.I).strip()
try:
remote_filesize = int(t.headers['Content-length'])
logger.fdebug('remote filesize: %s' % remote_filesize)
except Exception as e:
if 'go.php-urls' not in link:
link = re.sub('go.php-url=', 'go.php-urls', link)
t = s.get(link, verify=True, cookies=cf_cookievalue, headers=self.headers, stream=True, timeout=30)
filename = os.path.basename(urllib.unquote(t.url).decode('utf-8'))
if 'GetComics.INFO' in filename:
filename = re.sub('GetComics.INFO', '', filename, re.I).strip()
try:
remote_filesize = int(t.headers['Content-length'])
logger.fdebug('remote filesize: %s' % remote_filesize)
except Exception as e:
logger.warn('[WARNING] Unable to retrieve remote file size - this is usually due to the page being behind a different click-bait/ad page. Error returned as : %s' % e)
logger.warn('[WARNING] Considering this particular download as invalid and will ignore this result.')
remote_filesize = 0
mylar.DDL_LOCK = False
return ({"success": False,
"filename": filename,
"path": None})
else:
logger.warn('[WARNING] Unable to retrieve remote file size - this is usually due to the page being behind a different click-bait/ad page. Error returned as : %s' % e)
logger.warn('[WARNING] Considering this particular download as invalid and will ignore this result.')
remote_filesize = 0
mylar.DDL_LOCK = False
return ({"success": False,
"filename": filename,
"path": None})
#write the filename to the db for tracking purposes...
myDB.upsert('ddl_info', {'filename': filename, 'remote_filesize': remote_filesize}, {'id': id})
if mylar.CONFIG.DDL_LOCATION is not None and not os.path.isdir(mylar.CONFIG.DDL_LOCATION):
checkdirectory = mylar.filechecker.validateAndCreateDirectory(mylar.CONFIG.DDL_LOCATION, True)
if not checkdirectory:
logger.warn('[ABORTING] Error trying to validate/create DDL download directory: %s.' % mylar.CONFIG.DDL_LOCATION)
return ({"success": False,
"filename": filename,
"path": None})
path = os.path.join(mylar.CONFIG.DDL_LOCATION, filename)
if t.headers.get('content-encoding') == 'gzip': #.get('Content-Encoding') == 'gzip':
buf = StringIO(t.content)
f = gzip.GzipFile(fileobj=buf)
if resume is not None:
with open(path, 'ab') as f:
for chunk in t.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
f.flush()
else:
with open(path, 'wb') as f:
for chunk in t.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
f.flush()
except Exception as e:
logger.error('[ERROR] %s' % e)
mylar.DDL_LOCK = False
return ({"success": False,
"filename": filename,
"path": None})
else:
mylar.DDL_LOCK = False
if os.path.isfile(path):
if path.endswith('.zip'):
new_path = os.path.join(mylar.CONFIG.DDL_LOCATION, re.sub('.zip', '', filename).strip())
logger.info('Zip file detected. Unzipping into new modified path location: %s' % new_path)
try:
zip_f = zipfile.ZipFile(path, 'r')
zip_f.extractall(new_path)
zip_f.close()
except Exception as e:
logger.warn('[ERROR: %s] Unable to extract zip file: %s' % (e, new_path))
return ({"success": False,
"filename": filename,
"path": None})
else:
try:
os.remove(path)
except Exception as e:
logger.warn('[ERROR: %s] Unable to remove zip file from %s after extraction.' % (e, path))
filename = None
else:
new_path = path
return ({"success": True,
"filename": filename,
"path": new_path})
def issue_list(self, pack):
#packlist = [x.strip() for x in pack.split(',)]
packlist = pack.replace('+', ' ').replace(',', ' ').split()
print packlist
plist = []
pack_issues = []
for pl in packlist:
if '-' in pl:
plist.append(range(int(pl[:pl.find('-')]),int(pl[pl.find('-')+1:])+1))
else:
if 'TPBs' not in pl:
plist.append(int(pl))
else:
plist.append('TPBs')
for pi in plist:
if type(pi) == list:
for x in pi:
pack_issues.append(x)
else:
pack_issues.append(pi)
pack_issues.sort()
print "pack_issues: %s" % pack_issues
#if __name__ == '__main__':
# ab = GC(sys.argv[1]) #'justice league aquaman') #sys.argv[0])
# #c = ab.search()
# b = ab.loadsite('test', sys.argv[2])
# c = ab.parse_downloadresults('test', '60MB')
# #c = ab.issue_list(sys.argv[2])
| 21,682 | Python | .py | 417 | 33.529976 | 194 | 0.457828 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,226 | comicbookdb.py | evilhero_mylar/mylar/comicbookdb.py |
from bs4 import BeautifulSoup, UnicodeDammit
import urllib2
import re
import helpers
import logger
import datetime
import sys
from decimal import Decimal
from HTMLParser import HTMLParseError
from time import strptime
def cbdb(comicnm, ComicYear):
#comicnm = 'Animal Man'
#print ( "comicname: " + str(comicnm) )
#print ( "comicyear: " + str(comicyr) )
comicnm = re.sub(' ', '+', comicnm)
input = "http://mobile.comicbookdb.com/search.php?form_search=" + str(comicnm) + "&form_searchtype=Title&x=0&y=0"
response = urllib2.urlopen(input)
soup = BeautifulSoup(response)
abc = soup.findAll('a', href=True)
lenabc = len(abc)
i = 0
resultName = []
resultID = []
resultYear = []
resultIssues = []
resultURL = []
matched = "no"
while (i < lenabc):
titlet = abc[i] # iterate through the href's, pulling out only results.
print ("titlet: " + str(titlet))
if "title.php" in str(titlet):
print ("found title")
tempName = titlet.findNext(text=True)
print ("tempName: " + tempName)
resultName = tempName[:tempName.find("(")]
print ("ComicName: " + resultName)
resultYear = tempName[tempName.find("(") +1:tempName.find(")")]
if resultYear.isdigit(): pass
else:
i += 1
continue
print "ComicYear: " + resultYear
ID_som = titlet['href']
resultURL = ID_som
print "CBDB URL: " + resultURL
IDst = ID_som.find('?ID=')
resultID = ID_som[(IDst +4):]
print "CBDB ID: " + resultID
print ("resultname: " + resultName)
CleanComicName = re.sub('[\,\.\:\;\'\[\]\(\)\!\@\#\$\%\^\&\*\-\_\+\=\?\/]', '', comicnm)
CleanComicName = re.sub(' ', '', CleanComicName).lower()
CleanResultName = re.sub('[\,\.\:\;\'\[\]\(\)\!\@\#\$\%\^\&\*\-\_\+\=\?\/]', '', resultName)
CleanResultName = re.sub(' ', '', CleanResultName).lower()
print ("CleanComicName: " + CleanComicName)
print ("CleanResultName: " + CleanResultName)
if CleanResultName == CleanComicName or CleanResultName[3:] == CleanComicName or len(CleanComicName) == len(CleanResultName):
#if resultName[n].lower() == helpers.cleanName(str(ComicName)).lower():
print ("i:" + str(i) + "...matched by name to Mylar!")
print ("ComicYear: " + str(ComicYear) + ".. to ResultYear: " + str(resultYear))
if resultYear.isdigit():
if int(resultYear) == int(ComicYear) or int(resultYear) == int(ComicYear) +1:
resultID = str(resultID)
print ("Matchumundo!")
matched = "yes"
else:
continue
if matched == "yes":
break
i += 1
return IssueDetails(resultID)
def IssueDetails(cbdb_id):
annuals = {}
annualslist = []
gcount = 0
pagethis = 'http://comicbookdb.com/title.php?ID=' + str(cbdb_id)
response = urllib2.urlopen(pagethis)
soup = BeautifulSoup(response)
resultp = soup.findAll("table")
total = len(resultp) # -- number of tables
#get details here
startit = resultp[0].find("table", {"width": "884"})
i = 0
pubchk = 0
boop = startit.findAll('strong')
for t in boop:
if pubchk == 0:
if ("publisher.php?" in startit('a')[i]['href']):
print (startit('a')[i]['href'])
publisher = str(startit('a')[i].contents)
print ("publisher: " + publisher)
pubchk = "1"
elif 'Publication Date: ' in t:
pdi = boop[i].nextSibling
print ("publication date: " + pdi)
elif 'Number of issues cataloged: ' in t:
noi = boop[i].nextSibling
print ("number of issues: " + noi)
i += 1
if i > len(boop): break
# pd = startit.find("Publication Date: ").nextSibling.next.text
# resultPublished = str(pd)
# noi = startit.find("Number of issues cataloged: ").nextSibling.next.text
# totalIssues = str(noi)
# print ("Publication Dates : " + str(resultPublished))
# print ("Total Issues: " + str(totalIssues))
ti = 1 # start at one as 0 is the ENTIRE soup structure
while (ti < total):
#print result
if resultp[ti].find("a", {"class": "page_link"}):
#print "matcheroso"
tableno = resultp[ti].findAll('tr') # 7th table, all the tr's
#print ti, total
break
ti += 1
noresults = len(tableno)
#print ("tableno: " + str(tableno))
print ("there are " + str(noresults) + " issues total (cover variations, et all).")
i = 1 # start at 1 so we don't grab the table headers ;)
issue = []
storyarc = []
pubdate = []
#resultit = tableno[1]
#print ("resultit: " + str(resultit))
while (i < noresults):
resultit = tableno[i] # 7th table, 1st set of tr (which indicates an issue).
print ("resultit: " + str(resultit))
issuet = resultit.find("a", {"class": "page_link"}) # gets the issue # portion
try:
issue = issuet.findNext(text=True)
except:
print ("blank space - skipping")
i += 1
continue
if 'annual' not in issue.lower():
i += 1
continue
lent = resultit('a', href=True) #gathers all the a href's within this particular tr
#print ("lent: " + str(lent))
lengtht = len(lent) # returns the # of ahref's within this particular tr
#print ("lengtht: " + str(lengtht))
#since we don't know which one contains the story arc, we need to iterate through to find it
#we need to know story arc, because the following td is the Publication Date
n = 0
issuetitle = 'None'
while (n < lengtht):
storyt = lent[n] #
print ("storyt: " + str(storyt))
if 'issue.php' in storyt:
issuetitle = storyt.findNext(text=True)
print ("title:" + issuetitle)
if 'storyarc.php' in storyt:
#print ("found storyarc")
storyarc = storyt.findNext(text=True)
#print ("Story Arc: " + str(storyarc))
break
n += 1
pubd = resultit('td') # find all the <td>'s within this tr
publen = len(pubd) # find the # of <td>'s
pubs = pubd[publen -1] # take the last <td> which will always contain the publication date
pdaters = pubs.findNext(text=True) # get the actual date :)
basmonths = {'january': '01', 'february': '02', 'march': '03', 'april': '04', 'may': '05', 'june': '06', 'july': '07', 'august': '09', 'september': '10', 'october': '11', 'december': '12', 'annual': ''}
for numbs in basmonths:
if numbs in pdaters.lower():
pconv = basmonths[numbs]
ParseYear = re.sub('/s', '', pdaters[-5:])
if basmonths[numbs] == '':
pubdate = str(ParseYear)
else:
pubdate = str(ParseYear) + "-" + str(pconv)
# logger.fdebug("!success - Publication date: " + str(ParseDate))
#pubdate = re.sub("[^0-9]", "", pdaters)
issuetmp = re.sub("[^0-9]", '', issue)
print ("Issue : " + str(issuetmp) + " (" + str(pubdate) + ")")
print ("Issuetitle " + str(issuetitle))
annualslist.append({
'AnnualIssue': issuetmp.strip(),
'AnnualTitle': issuetitle,
'AnnualDate': pubdate.strip(),
'AnnualYear': ParseYear.strip()
})
gcount += 1
print("annualslist appended...")
i += 1
annuals['annualslist'] = annualslist
print ("Issues:" + str(annuals['annualslist']))
print ("There are " + str(gcount) + " issues.")
annuals['totalissues'] = gcount
annuals['GCDComicID'] = cbdb_id
return annuals
if __name__ == '__main__':
cbdb(sys.argv[1], sys.argv[2])
| 8,235 | Python | .py | 191 | 33.350785 | 210 | 0.545148 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,227 | latest.py | evilhero_mylar/mylar/latest.py | # just updating the sqlite db to latest issue / newest pull
from mylar import db
def latestcheck():
myDB = db.DBConnection()
comics = myDB.select('SELECT * from comics WHERE LatestIssue = 'None')
| 216 | Python | .py | 5 | 38.2 | 78 | 0.710145 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,228 | test.py | evilhero_mylar/mylar/test.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import re
import time
import shutil
import traceback
from base64 import b16encode, b32decode
import hashlib, StringIO
import bencode
from torrent.helpers.variable import link, symlink, is_rarfile
import requests
#from lib.unrar2 import RarFile
import torrent.clients.rtorrent as TorClient
import mylar
from mylar import logger, helpers
class RTorrent(object):
def __init__(self):
self.client = TorClient.TorrentClient()
if not self.client.connect(mylar.CONFIG.RTORRENT_HOST,
mylar.CONFIG.RTORRENT_USERNAME,
mylar.CONFIG.RTORRENT_PASSWORD,
mylar.CONFIG.RTORRENT_AUTHENTICATION,
mylar.CONFIG.RTORRENT_VERIFY,
mylar.CONFIG.RTORRENT_RPC_URL,
mylar.CONFIG.RTORRENT_CA_BUNDLE):
logger.error('[ERROR] Could not connect to %s - exiting' % mylar.CONFIG.RTORRENT_HOST)
sys.exit(-1)
def main(self, torrent_hash=None, filepath=None, check=False):
torrent = self.client.find_torrent(torrent_hash)
if torrent:
if check:
logger.fdebug('Successfully located torrent %s by hash on client. Detailed statistics to follow' % torrent_hash)
else:
logger.warn("%s Torrent already exists. Not downloading at this time." % torrent_hash)
return
else:
if check:
logger.warn('Unable to locate torrent with a hash value of %s' % torrent_hash)
return
if filepath:
loadit = self.client.load_torrent(filepath)
if loadit:
if filepath.startswith('magnet'):
torrent_hash = re.findall("urn:btih:([\w]{32,40})", filepath)[0]
if len(torrent_hash) == 32:
torrent_hash = b16encode(b32decode(torrent_hash)).lower()
torrent_hash = torrent_hash.upper()
else:
torrent_hash = self.get_the_hash(filepath)
else:
return
torrent = self.client.find_torrent(torrent_hash)
if torrent is None:
logger.warn('Couldn\'t find torrent with hash: %s' % torrent_hash)
sys.exit(-1)
torrent_info = self.client.get_torrent(torrent)
if check:
return torrent_info
if torrent_info['completed']:
logger.fdebug('Directory: %s' % torrent_info['folder'])
logger.fdebug('Name: %s' % torrent_info['name'])
logger.fdebug('FileSize: %s' % helpers.human_size(torrent_info['total_filesize']))
logger.fdebug('Completed: %s' % torrent_info['completed'])
logger.fdebug('Downloaded: %s' % helpers.human_size(torrent_info['download_total']))
logger.fdebug('Uploaded: %s' % helpers.human_size(torrent_info['upload_total']))
logger.fdebug('Ratio: %s' % torrent_info['ratio'])
#logger.info('Time Started: %s' % torrent_info['time_started'])
logger.fdebug('Seeding Time: %s' % helpers.humanize_time(int(time.time()) - torrent_info['time_started']))
if torrent_info['label']:
logger.fdebug('Torrent Label: %s' % torrent_info['label'])
#logger.info(torrent_info)
return torrent_info
def get_the_hash(self, filepath):
# Open torrent file
torrent_file = open(filepath, "rb")
metainfo = bencode.decode(torrent_file.read())
info = metainfo['info']
thehash = hashlib.sha1(bencode.encode(info)).hexdigest().upper()
logger.fdebug('Hash: %s' % thehash)
return thehash
| 4,448 | Python | .py | 94 | 36.776596 | 128 | 0.617193 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,229 | sabnzbd.py | evilhero_mylar/mylar/sabnzbd.py | #!/usr/bin/python
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import urllib
import requests
import ntpath
import os
import sys
import re
import time
import logger
import mylar
class SABnzbd(object):
def __init__(self, params):
#self.sab_url = sab_host + '/api'
#self.sab_apikey = 'e90f54f4f757447a20a4fa89089a83ed'
self.sab_url = mylar.CONFIG.SAB_HOST + '/api'
self.params = params
def sender(self):
try:
from requests.packages.urllib3 import disable_warnings
disable_warnings()
except:
logger.info('Unable to disable https warnings. Expect some spam if using https nzb providers.')
try:
logger.info('parameters set to %s' % self.params)
logger.info('sending now to %s' % self.sab_url)
sendit = requests.post(self.sab_url, data=self.params, verify=False)
except:
logger.info('Failed to send to client.')
return {'status': False}
else:
sendresponse = sendit.json()
logger.info(sendresponse)
if sendresponse['status'] is True:
queue_params = {'status': True,
'nzo_id': ''.join(sendresponse['nzo_ids']),
'queue': {'mode': 'queue',
'search': ''.join(sendresponse['nzo_ids']),
'output': 'json',
'apikey': mylar.CONFIG.SAB_APIKEY}}
else:
queue_params = {'status': False}
return queue_params
def processor(self):
sendresponse = self.params['nzo_id']
try:
logger.info('sending now to %s' % self.sab_url)
logger.info('parameters set to %s' % self.params)
time.sleep(5) #pause 5 seconds before monitoring just so it hits the queue
h = requests.get(self.sab_url, params=self.params['queue'], verify=False)
except Exception as e:
logger.info('uh-oh: %s' % e)
return self.historycheck(self.params)
else:
queueresponse = h.json()
logger.info('successfully queried the queue for status')
try:
queueinfo = queueresponse['queue']
#logger.fdebug('queue: %s' % queueinfo)
logger.fdebug('Queue status : %s' % queueinfo['status'])
logger.fdebug('Queue mbleft : %s' % queueinfo['mbleft'])
while any([str(queueinfo['status']) == 'Downloading', str(queueinfo['status']) == 'Idle']) and float(queueinfo['mbleft']) > 0:
#if 'comicrn' in queueinfo['script'].lower():
# logger.warn('ComicRN has been detected as being active for this category & download. Completed Download Handling will NOT be performed due to this.')
# logger.warn('Either disable Completed Download Handling for SABnzbd within Mylar, or remove ComicRN from your category script in SABnzbd.')
# return {'status': 'double-pp', 'failed': False}
#logger.fdebug('queue_params: %s' % self.params['queue'])
queue_resp = requests.get(self.sab_url, params=self.params['queue'], verify=False)
queueresp = queue_resp.json()
queueinfo = queueresp['queue']
logger.fdebug('status: %s' % queueinfo['status'])
logger.fdebug('mbleft: %s' % queueinfo['mbleft'])
logger.fdebug('timeleft: %s' % queueinfo['timeleft'])
logger.fdebug('eta: %s' % queueinfo['eta'])
time.sleep(5)
except Exception as e:
logger.warn('error: %s' % e)
logger.info('File has now downloaded!')
return self.historycheck(self.params)
def historycheck(self, nzbinfo):
sendresponse = nzbinfo['nzo_id']
hist_params = {'mode': 'history',
'category': mylar.CONFIG.SAB_CATEGORY,
'failed': 0,
'output': 'json',
'apikey': mylar.CONFIG.SAB_APIKEY}
hist = requests.get(self.sab_url, params=hist_params, verify=False)
historyresponse = hist.json()
#logger.info(historyresponse)
histqueue = historyresponse['history']
found = {'status': False}
while found['status'] is False:
try:
for hq in histqueue['slots']:
#logger.info('nzo_id: %s --- %s [%s]' % (hq['nzo_id'], sendresponse, hq['status']))
if hq['nzo_id'] == sendresponse and any([hq['status'] == 'Completed', hq['status'] == 'Running', 'comicrn' in hq['script'].lower()]):
logger.info('found matching completed item in history. Job has a status of %s' % hq['status'])
if 'comicrn' in hq['script'].lower():
logger.warn('ComicRN has been detected as being active for this category & download. Completed Download Handling will NOT be performed due to this.')
logger.warn('Either disable Completed Download Handling for SABnzbd within Mylar, or remove ComicRN from your category script in SABnzbd.')
return {'status': 'double-pp', 'failed': False}
if os.path.isfile(hq['storage']):
logger.info('location found @ %s' % hq['storage'])
found = {'status': True,
'name': ntpath.basename(hq['storage']), #os.pathre.sub('.nzb', '', hq['nzb_name']).strip(),
'location': os.path.abspath(os.path.join(hq['storage'], os.pardir)),
'failed': False,
'issueid': nzbinfo['issueid'],
'comicid': nzbinfo['comicid'],
'apicall': True,
'ddl': False}
break
else:
logger.info('no file found where it should be @ %s - is there another script that moves things after completion ?' % hq['storage'])
return {'status': 'file not found', 'failed': False}
elif hq['nzo_id'] == sendresponse and hq['status'] == 'Failed':
#get the stage / error message and see what we can do
stage = hq['stage_log']
for x in stage[0]:
if 'Failed' in x['actions'] and any([x['name'] == 'Unpack', x['name'] == 'Repair']):
if 'moving' in x['actions']:
logger.warn('There was a failure in SABnzbd during the unpack/repair phase that caused a failure: %s' % x['actions'])
else:
logger.warn('Failure occured during the Unpack/Repair phase of SABnzbd. This is probably a bad file: %s' % x['actions'])
if mylar.FAILED_DOWNLOAD_HANDLING is True:
found = {'status': True,
'name': re.sub('.nzb', '', hq['nzb_name']).strip(),
'location': os.path.abspath(os.path.join(hq['storage'], os.pardir)),
'failed': True,
'issueid': sendresponse['issueid'],
'comicid': sendresponse['comicid'],
'apicall': True,
'ddl': False}
break
break
except Exception as e:
logger.warn('error %s' % e)
return {'status': False, 'failed': False}
return found
| 8,883 | Python | .py | 152 | 40.328947 | 177 | 0.509464 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,230 | dbupdater.py | evilhero_mylar/mylar/dbupdater.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import mylar
from mylar import logger, helpers
#import threading
class dbUpdate():
def __init__(self, sched):
pass
def run(self, sched):
logger.info('[DBUpdate] Updating Database.')
helpers.job_management(write=True, job='DB Updater', current_run=helpers.utctimestamp(), status='Running')
mylar.updater.dbUpdate(sched=sched)
helpers.job_management(write=True, job='DB Updater', last_run_completed=helpers.utctimestamp(), status='Waiting')
| 1,176 | Python | .py | 26 | 42.153846 | 121 | 0.748252 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,231 | encrypted.py | evilhero_mylar/mylar/encrypted.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import random
import base64
import re
import sys
import os
import mylar
from mylar import logger
class Encryptor(object):
def __init__(self, password, chk_password=None):
self.password = password.encode('utf-8')
def encrypt_it(self):
try:
salt = os.urandom(8)
saltedhash = [salt[i] for i in range (0, len(salt))]
salted_pass = base64.b64encode('%s%s' % (self.password,salt))
except Exception as e:
logger.warn('Error when encrypting: %s' % e)
return {'status': False}
else:
return {'status': True, 'password': '^~$z$' + salted_pass}
def decrypt_it(self):
try:
if not self.password.startswith('^~$z$'):
logger.warn('Error not an encryption that I recognize.')
return {'status': False}
passd = base64.b64decode(self.password[5:]) #(base64.decodestring(self.password))
saltedhash = [bytes(passd[-8:])]
except Exception as e:
logger.warn('Error when decrypting password: %s' % e)
return {'status': False}
else:
return {'status': True, 'password': passd[:-8]}
| 1,888 | Python | .py | 48 | 33.520833 | 92 | 0.651391 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,232 | importer.py | evilhero_mylar/mylar/importer.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import time
import os, errno
import sys
import shlex
import datetime
import re
import json
import urllib
import urllib2
import shutil
import imghdr
import sqlite3
import cherrypy
import requests
import mylar
from mylar import logger, filers, helpers, db, mb, cv, parseit, filechecker, search, updater, moveit, comicbookdb
def is_exists(comicid):
myDB = db.DBConnection()
# See if the artist is already in the database
comiclist = myDB.select('SELECT ComicID, ComicName from comics WHERE ComicID=?', [comicid])
if any(comicid in x for x in comiclist):
logger.info(comiclist[0][1] + ' is already in the database.')
return False
else:
return False
def addComictoDB(comicid, mismatch=None, pullupd=None, imported=None, ogcname=None, calledfrom=None, annload=None, chkwant=None, issuechk=None, issuetype=None, latestissueinfo=None, csyear=None, fixed_type=None):
myDB = db.DBConnection()
controlValueDict = {"ComicID": comicid}
dbcomic = myDB.selectone('SELECT * FROM comics WHERE ComicID=?', [comicid]).fetchone()
if dbcomic is None:
newValueDict = {"ComicName": "Comic ID: %s" % (comicid),
"Status": "Loading"}
if all([imported is not None, mylar.CONFIG.IMP_PATHS is True]):
comlocation = os.path.dirname(imported['filelisting'][0]['comiclocation'])
else:
comlocation = None
oldcomversion = None
series_status = 'Loading'
lastissueid = None
aliases = None
else:
if chkwant is not None:
logger.fdebug('ComicID: ' + str(comicid) + ' already exists. Not adding from the future pull list at this time.')
return 'Exists'
if dbcomic['Status'] == 'Active':
series_status = 'Active'
elif dbcomic['Status'] == 'Paused':
series_status = 'Paused'
else:
series_status = 'Loading'
newValueDict = {"Status": "Loading"}
comlocation = dbcomic['ComicLocation']
lastissueid = dbcomic['LatestIssueID']
aliases = dbcomic['AlternateSearch']
logger.info('aliases currently: %s' % aliases)
if not latestissueinfo:
latestissueinfo = []
latestissueinfo.append({"latestiss": dbcomic['LatestIssue'],
"latestdate": dbcomic['LatestDate']})
if mylar.CONFIG.CREATE_FOLDERS is True:
checkdirectory = filechecker.validateAndCreateDirectory(comlocation, True)
if not checkdirectory:
logger.warn('Error trying to validate/create directory. Aborting this process at this time.')
return
oldcomversion = dbcomic['ComicVersion'] #store the comicversion and chk if it exists before hammering.
myDB.upsert("comics", newValueDict, controlValueDict)
#run the re-sortorder here in order to properly display the page
if all([pullupd is None, calledfrom != 'maintenance']):
helpers.ComicSort(comicorder=mylar.COMICSORT, imported=comicid)
# we need to lookup the info for the requested ComicID in full now
comic = cv.getComic(comicid, 'comic')
if not comic:
logger.warn('Error fetching comic. ID for : ' + comicid)
if dbcomic is None:
newValueDict = {"ComicName": "Fetch failed, try refreshing. (%s)" % (comicid),
"Status": "Active"}
else:
if series_status == 'Active' or series_status == 'Loading':
newValueDict = {"Status": "Active"}
myDB.upsert("comics", newValueDict, controlValueDict)
return
if comic['ComicName'].startswith('The '):
sortname = comic['ComicName'][4:]
else:
sortname = comic['ComicName']
comic['Corrected_Type'] = fixed_type
if fixed_type is not None and fixed_type != comic['Type']:
logger.info('Forced Comic Type to : %s' % comic['Corrected_Type'])
logger.info('Now adding/updating: ' + comic['ComicName'])
#--Now that we know ComicName, let's try some scraping
#--Start
# gcd will return issue details (most importantly publishing date)
if not mylar.CONFIG.CV_ONLY:
if mismatch == "no" or mismatch is None:
gcdinfo=parseit.GCDScraper(comic['ComicName'], comic['ComicYear'], comic['ComicIssues'], comicid)
#print ("gcdinfo: " + str(gcdinfo))
mismatch_com = "no"
if gcdinfo == "No Match":
updater.no_searchresults(comicid)
nomatch = "true"
logger.info('There was an error when trying to add ' + comic['ComicName'] + ' (' + comic['ComicYear'] + ')')
return nomatch
else:
mismatch_com = "yes"
#print ("gcdinfo:" + str(gcdinfo))
elif mismatch == "yes":
CV_EXcomicid = myDB.selectone("SELECT * from exceptions WHERE ComicID=?", [comicid])
if CV_EXcomicid['variloop'] is None: pass
else:
vari_loop = CV_EXcomicid['variloop']
NewComicID = CV_EXcomicid['NewComicID']
gcomicid = CV_EXcomicid['GComicID']
resultURL = "/series/" + str(NewComicID) + "/"
#print ("variloop" + str(CV_EXcomicid['variloop']))
#if vari_loop == '99':
gcdinfo = parseit.GCDdetails(comseries=None, resultURL=resultURL, vari_loop=0, ComicID=comicid, TotalIssues=0, issvariation="no", resultPublished=None)
# print ("Series Published" + parseit.resultPublished)
CV_NoYearGiven = "no"
#if the SeriesYear returned by CV is blank or none (0000), let's use the gcd one.
if any([comic['ComicYear'] is None, comic['ComicYear'] == '0000', comic['ComicYear'][-1:] == '-']):
if mylar.CONFIG.CV_ONLY:
#we'll defer this until later when we grab all the issues and then figure it out
logger.info('Uh-oh. I cannot find a Series Year for this series. I am going to try analyzing deeper.')
SeriesYear = cv.getComic(comicid, 'firstissue', comic['FirstIssueID'])
if SeriesYear == '0000':
logger.info('Ok - I could not find a Series Year at all. Loading in the issue data now and will figure out the Series Year.')
CV_NoYearGiven = "yes"
issued = cv.getComic(comicid, 'issue')
SeriesYear = issued['firstdate'][:4]
else:
SeriesYear = gcdinfo['SeriesYear']
else:
SeriesYear = comic['ComicYear']
if any([int(SeriesYear) > int(datetime.datetime.now().year) + 1, int(SeriesYear) == 2099]) and csyear is not None:
logger.info('Corrected year of ' + str(SeriesYear) + ' to corrected year for series that was manually entered previously of ' + str(csyear))
SeriesYear = csyear
logger.info('Successfully retrieved details for ' + comic['ComicName'])
#since the weekly issue check could return either annuals or issues, let's initialize it here so it carries through properly.
weeklyissue_check = []
if any([oldcomversion is None, oldcomversion == "None"]):
logger.info('Previous version detected as None - seeing if update required')
if comic['ComicVersion'].isdigit():
comicVol = 'v' + comic['ComicVersion']
logger.info('Updated version to :' + str(comicVol))
if all([mylar.CONFIG.SETDEFAULTVOLUME is False, comicVol == 'v1']):
comicVol = None
else:
if mylar.CONFIG.SETDEFAULTVOLUME is True:
comicVol = 'v1'
else:
comicVol = None
else:
comicVol = oldcomversion
if all([mylar.CONFIG.SETDEFAULTVOLUME is True, comicVol is None]):
comicVol = 'v1'
# setup default location here
u_comicnm = comic['ComicName']
# let's remove the non-standard characters here that will break filenaming / searching.
comicname_filesafe = helpers.filesafe(u_comicnm)
if comlocation is None:
comic_values = {'ComicName': comic['ComicName'],
'ComicPublisher': comic['ComicPublisher'],
'ComicYear': SeriesYear,
'ComicVersion': comicVol,
'Type': comic['Type'],
'Corrected_Type': comic['Corrected_Type']}
dothedew = filers.FileHandlers(comic=comic_values)
comlocation = dothedew.folder_create()
#moved this out of the above loop so it will chk for existance of comlocation in case moved
#if it doesn't exist - create it (otherwise will bugger up later on)
if os.path.isdir(comlocation):
logger.info('Directory (' + comlocation + ') already exists! Continuing...')
else:
if mylar.CONFIG.CREATE_FOLDERS is True:
checkdirectory = filechecker.validateAndCreateDirectory(comlocation, True)
if not checkdirectory:
logger.warn('Error trying to validate/create directory. Aborting this process at this time.')
return
#try to account for CV not updating new issues as fast as GCD
#seems CV doesn't update total counts
#comicIssues = gcdinfo['totalissues']
comicIssues = comic['ComicIssues']
if not mylar.CONFIG.CV_ONLY:
if gcdinfo['gcdvariation'] == "cv":
comicIssues = str(int(comic['ComicIssues']) + 1)
if mylar.CONFIG.ALTERNATE_LATEST_SERIES_COVERS is False:
cimage = os.path.join(mylar.CONFIG.CACHE_DIR, str(comicid) + '.jpg')
PRComicImage = os.path.join('cache', str(comicid) + ".jpg")
ComicImage = helpers.replacetheslash(PRComicImage)
if os.path.isfile(cimage) is True:
logger.fdebug('Cover already exists for series. Not redownloading.')
else:
covercheck = helpers.getImage(comicid, comic['ComicImage'])
if covercheck == 'retry':
logger.info('Attempting to retrieve alternate comic image for the series.')
covercheck = helpers.getImage(comicid, comic['ComicImageALT'])
#if the comic cover local is checked, save a cover.jpg to the series folder.
if all([mylar.CONFIG.COMIC_COVER_LOCAL is True, os.path.isdir(comlocation) is True, os.path.isfile(os.path.join(comlocation, 'cover.jpg')) is False]):
try:
comiclocal = os.path.join(comlocation, 'cover.jpg')
shutil.copyfile(cimage, comiclocal)
if mylar.CONFIG.ENFORCE_PERMS:
filechecker.setperms(comiclocal)
except IOError as e:
logger.error('Unable to save cover (%s) into series directory (%s) at this time.' % (cimage, comiclocal))
else:
ComicImage = None
#for description ...
#Cdesc = helpers.cleanhtml(comic['ComicDescription'])
#cdes_find = Cdesc.find("Collected")
#cdes_removed = Cdesc[:cdes_find]
#logger.fdebug('description: ' + cdes_removed)
#dynamic-name generation here.
as_d = filechecker.FileChecker(watchcomic=comic['ComicName'])
as_dinfo = as_d.dynamic_replace(comic['ComicName'])
tmpseriesname = as_dinfo['mod_seriesname']
dynamic_seriesname = re.sub('[\|\s]','', tmpseriesname.lower()).strip()
if comic['Issue_List'] != 'None':
issue_list = json.dumps(comic['Issue_List'])
else:
issue_list = None
if comic['Aliases'] != 'None':
if all([aliases is not None, aliases != 'None']):
for x in aliases.split('##'):
aliaschk = [x for y in comic['Aliases'].split('##') if y == x]
if aliaschk and x not in aliases.split('##'):
aliases += '##' + ''.join(x)
else:
if x not in aliases.split('##'):
aliases += '##' + x
else:
aliases = comic['Aliases']
else:
aliases = aliases
logger.fdebug('comicIssues: %s' % comicIssues)
logger.fdebug('seriesyear: %s / currentyear: %s' % (SeriesYear, helpers.today()[:4]))
logger.fdebug('comicType: %s' % comic['Type'])
if all([int(comicIssues) == 1, SeriesYear < helpers.today()[:4], comic['Type'] != 'One-Shot', comic['Type'] != 'TPB']):
logger.info('Determined to be a one-shot issue. Forcing Edition to One-Shot')
booktype = 'One-Shot'
else:
booktype = comic['Type']
controlValueDict = {"ComicID": comicid}
newValueDict = {"ComicName": comic['ComicName'],
"ComicSortName": sortname,
"ComicName_Filesafe": comicname_filesafe,
"DynamicComicName": dynamic_seriesname,
"ComicYear": SeriesYear,
"ComicImage": ComicImage,
"ComicImageURL": comic.get("ComicImage", ""),
"ComicImageALTURL": comic.get("ComicImageALT", ""),
"Total": comicIssues,
"ComicVersion": comicVol,
"ComicLocation": comlocation,
"ComicPublisher": comic['ComicPublisher'],
# "Description": Cdesc, #.dencode('utf-8', 'replace'),
"DetailURL": comic['ComicURL'],
"AlternateSearch": aliases,
# "ComicPublished": gcdinfo['resultPublished'],
"ComicPublished": "Unknown",
"Type": booktype,
"Corrected_Type": comic['Corrected_Type'],
"Collects": issue_list,
"DateAdded": helpers.today(),
"Status": "Loading"}
myDB.upsert("comics", newValueDict, controlValueDict)
#comicsort here...
#run the re-sortorder here in order to properly display the page
if all([pullupd is None, calledfrom != 'maintenance']):
helpers.ComicSort(sequence='update')
if CV_NoYearGiven == 'no':
#if set to 'no' then we haven't pulled down the issues, otherwise we did it already
issued = cv.getComic(comicid, 'issue')
if issued is None:
logger.warn('Unable to retrieve data from ComicVine. Get your own API key already!')
return
logger.info('Sucessfully retrieved issue details for ' + comic['ComicName'])
#move to own function so can call independently to only refresh issue data
#issued is from cv.getComic, comic['ComicName'] & comicid would both be already known to do independent call.
updateddata = updateissuedata(comicid, comic['ComicName'], issued, comicIssues, calledfrom, SeriesYear=SeriesYear, latestissueinfo=latestissueinfo)
issuedata = updateddata['issuedata']
anndata = updateddata['annualchk']
nostatus = updateddata['nostatus']
importantdates = updateddata['importantdates']
if issuedata is None:
logger.warn('Unable to complete Refreshing / Adding issue data - this WILL create future problems if not addressed.')
return {'status': 'incomplete'}
if any([calledfrom is None, calledfrom == 'maintenance']):
issue_collection(issuedata, nostatus='False')
#need to update annuals at this point too....
if anndata:
manualAnnual(annchk=anndata)
if mylar.CONFIG.ALTERNATE_LATEST_SERIES_COVERS is True: #, lastissueid != importantdates['LatestIssueID']]):
if os.path.join(mylar.CONFIG.CACHE_DIR, comicid + '.jpg') is True:
cover_modtime = datetime.datetime.utcfromtimestamp(os.path.getmtime(os.path.join(mylar.CONFIG.CACHE_DIR, comicid + '.jpg')))
cover_mtime = datetime.datetime.strftime(cover_modtime, '%Y-%m-%d')
if importantdates['LatestStoreDate'] != '0000-00-00':
lsd = re.sub('-', '', importantdates['LatestStoreDate']).strip()
else:
lsd = re.sub('-', '', importantdates['LatestDate']).strip()
if re.sub('-', '', cover_mtime).strip() < lsd:
logger.info('Attempting to retrieve new issue cover for display')
image_it(comicid, importantdates['LatestIssueID'], comlocation, comic['ComicImage'])
else:
logger.fdebug('no update required - lastissueid [%s] = latestissueid [%s]' % (lastissueid, importantdates['LatestIssueID']))
else:
image_it(comicid, importantdates['LatestIssueID'], comlocation, comic['ComicImage'])
else:
logger.fdebug('no update required - lastissueid [%s] = latestissueid [%s]' % (lastissueid, importantdates['LatestIssueID']))
if (mylar.CONFIG.CVINFO or (mylar.CONFIG.CV_ONLY and mylar.CONFIG.CVINFO)) and os.path.isdir(comlocation):
if os.path.isfile(os.path.join(comlocation, "cvinfo")) is False:
with open(os.path.join(comlocation, "cvinfo"), "w") as text_file:
text_file.write(str(comic['ComicURL']))
if calledfrom == 'weekly':
logger.info('Successfully refreshed ' + comic['ComicName'] + ' (' + str(SeriesYear) + '). Returning to Weekly issue comparison.')
logger.info('Update issuedata for ' + str(issuechk) + ' of : ' + str(weeklyissue_check))
return {'status': 'complete',
'issuedata': issuedata} # this should be the weeklyissue_check data from updateissuedata function
elif calledfrom == 'dbupdate':
logger.info('returning to dbupdate module')
return {'status': 'complete',
'issuedata': issuedata,
'anndata': anndata } # this should be the issuedata data from updateissuedata function
elif calledfrom == 'weeklycheck':
logger.info('Successfully refreshed ' + comic['ComicName'] + ' (' + str(SeriesYear) + '). Returning to Weekly issue update.')
return #no need to return any data here.
logger.info('Updating complete for: ' + comic['ComicName'])
#if it made it here, then the issuedata contains dates, let's pull the data now.
latestiss = importantdates['LatestIssue']
latestdate = importantdates['LatestDate']
lastpubdate = importantdates['LastPubDate']
series_status = importantdates['SeriesStatus']
#move the files...if imported is not empty & not futurecheck (meaning it's not from the mass importer.)
#logger.info('imported is : ' + str(imported))
if imported is None or imported == 'None' or imported == 'futurecheck':
pass
else:
if mylar.CONFIG.IMP_MOVE:
logger.info('Mass import - Move files')
moveit.movefiles(comicid, comlocation, imported)
else:
logger.info('Mass import - Moving not Enabled. Setting Archived Status for import.')
moveit.archivefiles(comicid, comlocation, imported)
#check for existing files...
statbefore = myDB.selectone("SELECT Status FROM issues WHERE ComicID=? AND Int_IssueNumber=?", [comicid, helpers.issuedigits(latestiss)]).fetchone()
logger.fdebug('issue: ' + latestiss + ' status before chk :' + str(statbefore['Status']))
updater.forceRescan(comicid)
statafter = myDB.selectone("SELECT Status FROM issues WHERE ComicID=? AND Int_IssueNumber=?", [comicid, helpers.issuedigits(latestiss)]).fetchone()
logger.fdebug('issue: ' + latestiss + ' status after chk :' + str(statafter['Status']))
logger.fdebug('pullupd: ' + str(pullupd))
logger.fdebug('lastpubdate: ' + str(lastpubdate))
logger.fdebug('series_status: ' + str(series_status))
if pullupd is None:
# lets' check the pullist for anything at this time as well since we're here.
# do this for only Present comics....
if mylar.CONFIG.AUTOWANT_UPCOMING and lastpubdate == 'Present' and series_status == 'Active': #and 'Present' in gcdinfo['resultPublished']:
logger.fdebug('latestissue: #' + str(latestiss))
chkstats = myDB.selectone("SELECT * FROM issues WHERE ComicID=? AND Int_IssueNumber=?", [comicid, helpers.issuedigits(latestiss)]).fetchone()
if chkstats is None:
if mylar.CONFIG.ANNUALS_ON:
chkstats = myDB.selectone("SELECT * FROM annuals WHERE ComicID=? AND Int_IssueNumber=?", [comicid, helpers.issuedigits(latestiss)]).fetchone()
if chkstats:
logger.fdebug('latestissue status: ' + chkstats['Status'])
if chkstats['Status'] == 'Skipped' or chkstats['Status'] == 'Wanted' or chkstats['Status'] == 'Snatched':
logger.info('Checking this week pullist for new issues of ' + comic['ComicName'])
if comic['ComicName'] != comicname_filesafe:
cn_pull = comicname_filesafe
else:
cn_pull = comic['ComicName']
updater.newpullcheck(ComicName=cn_pull, ComicID=comicid, issue=latestiss)
#here we grab issues that have been marked as wanted above...
if calledfrom != 'maintenance':
results = []
issresults = myDB.select("SELECT * FROM issues where ComicID=? AND Status='Wanted'", [comicid])
if issresults:
for issr in issresults:
results.append({'IssueID': issr['IssueID'],
'Issue_Number': issr['Issue_Number'],
'Status': issr['Status']
})
if mylar.CONFIG.ANNUALS_ON:
an_results = myDB.select("SELECT * FROM annuals WHERE ComicID=? AND Status='Wanted'", [comicid])
if an_results:
for ar in an_results:
results.append({'IssueID': ar['IssueID'],
'Issue_Number': ar['Issue_Number'],
'Status': ar['Status']
})
if results:
logger.info('Attempting to grab wanted issues for : ' + comic['ComicName'])
for result in results:
logger.fdebug('Searching for : ' + str(result['Issue_Number']))
logger.fdebug('Status of : ' + str(result['Status']))
search.searchforissue(result['IssueID'])
else: logger.info('No issues marked as wanted for ' + comic['ComicName'])
logger.info('Finished grabbing what I could.')
else:
logger.info('Already have the latest issue : #' + str(latestiss))
if chkwant is not None:
#if this isn't None, this is being called from the futureupcoming list
#a new series was added automagically, but it has more than 1 issue (probably because it was a back-dated issue)
#the chkwant is a tuple containing all the data for the given series' issues that were marked as Wanted for futureupcoming dates.
chkresults = myDB.select("SELECT * FROM issues WHERE ComicID=? AND Status='Skipped'", [comicid])
if chkresults:
logger.info('[FROM THE FUTURE CHECKLIST] Attempting to grab wanted issues for : ' + comic['ComicName'])
for result in chkresults:
for chkit in chkwant:
logger.fdebug('checking ' + chkit['IssueNumber'] + ' against ' + result['Issue_Number'])
if chkit['IssueNumber'] == result['Issue_Number']:
logger.fdebug('Searching for : ' + result['Issue_Number'])
logger.fdebug('Status of : ' + str(result['Status']))
search.searchforissue(result['IssueID'])
else: logger.info('No issues marked as wanted for ' + comic['ComicName'])
logger.info('Finished grabbing what I could.')
if imported == 'futurecheck':
logger.info('Returning to Future-Check module to complete the add & remove entry.')
return
elif all([imported is not None, imported != 'None']):
logger.info('Successfully imported : ' + comic['ComicName'])
return
if calledfrom == 'addbyid':
logger.info('Sucessfully added %s (%s) to the watchlist by directly using the ComicVine ID' % (comic['ComicName'], SeriesYear))
return {'status': 'complete'}
elif calledfrom == 'maintenance':
logger.info('Sucessfully added %s (%s) to the watchlist' % (comic['ComicName'], SeriesYear))
return {'status': 'complete',
'comicname': comic['ComicName'],
'year': SeriesYear}
else:
logger.info('Sucessfully added %s (%s) to the watchlist' % (comic['ComicName'], SeriesYear))
return {'status': 'complete'}
# if imported['Volume'] is None or imported['Volume'] == 'None':
# results = myDB.select("SELECT * FROM importresults WHERE (WatchMatch is Null OR WatchMatch LIKE 'C%') AND DynamicName=? AND Volume IS NULL",[imported['DynamicName']])
# else:
# if not imported['Volume'].lower().startswith('v'):
# volume = 'v' + str(imported['Volume'])
# results = myDB.select("SELECT * FROM importresults WHERE (WatchMatch is Null OR WatchMatch LIKE 'C%') AND DynamicName=? AND Volume=?",[imported['DynamicName'],imported['Volume']])
#
# if results is not None:
# for result in results:
# controlValue = {"DynamicName": imported['DynamicName'],
# "Volume": imported['Volume']}
# newValue = {"Status": "Imported",
# "SRID": result['SRID'],
# "ComicID": comicid}
# myDB.upsert("importresults", newValue, controlValue)
def GCDimport(gcomicid, pullupd=None, imported=None, ogcname=None):
# this is for importing via GCD only and not using CV.
# used when volume spanning is discovered for a Comic (and can't be added using CV).
# Issue Counts are wrong (and can't be added).
# because Comicvine ComicID and GCD ComicID could be identical at some random point, let's distinguish.
# CV = comicid, GCD = gcomicid :) (ie. CV=2740, GCD=G3719)
gcdcomicid = gcomicid
myDB = db.DBConnection()
# We need the current minimal info in the database instantly
# so we don't throw a 500 error when we redirect to the artistPage
controlValueDict = {"ComicID": gcdcomicid}
comic = myDB.selectone('SELECT ComicName, ComicYear, Total, ComicPublished, ComicImage, ComicLocation, ComicPublisher FROM comics WHERE ComicID=?', [gcomicid]).fetchone()
ComicName = comic[0]
ComicYear = comic[1]
ComicIssues = comic[2]
ComicPublished = comic[3]
comlocation = comic[5]
ComicPublisher = comic[6]
#ComicImage = comic[4]
#print ("Comic:" + str(ComicName))
newValueDict = {"Status": "Loading"}
myDB.upsert("comics", newValueDict, controlValueDict)
# we need to lookup the info for the requested ComicID in full now
#comic = cv.getComic(comicid,'comic')
if not comic:
logger.warn('Error fetching comic. ID for : ' + gcdcomicid)
if dbcomic is None:
newValueDict = {"ComicName": "Fetch failed, try refreshing. (%s)" % (gcdcomicid),
"Status": "Active"}
else:
newValueDict = {"Status": "Active"}
myDB.upsert("comics", newValueDict, controlValueDict)
return
#run the re-sortorder here in order to properly display the page
if pullupd is None:
helpers.ComicSort(comicorder=mylar.COMICSORT, imported=gcomicid)
if ComicName.startswith('The '):
sortname = ComicName[4:]
else:
sortname = ComicName
logger.info(u"Now adding/updating: " + ComicName)
#--Now that we know ComicName, let's try some scraping
#--Start
# gcd will return issue details (most importantly publishing date)
comicid = gcomicid[1:]
resultURL = "/series/" + str(comicid) + "/"
gcdinfo=parseit.GCDdetails(comseries=None, resultURL=resultURL, vari_loop=0, ComicID=gcdcomicid, TotalIssues=ComicIssues, issvariation=None, resultPublished=None)
if gcdinfo == "No Match":
logger.warn("No matching result found for " + ComicName + " (" + ComicYear + ")")
updater.no_searchresults(gcomicid)
nomatch = "true"
return nomatch
logger.info(u"Sucessfully retrieved details for " + ComicName)
# print ("Series Published" + parseit.resultPublished)
#--End
ComicImage = gcdinfo['ComicImage']
#comic book location on machine
# setup default location here
if comlocation is None:
# let's remove the non-standard characters here.
u_comicnm = ComicName
u_comicname = u_comicnm.encode('ascii', 'ignore').strip()
if ':' in u_comicname or '/' in u_comicname or ',' in u_comicname:
comicdir = u_comicname
if ':' in comicdir:
comicdir = comicdir.replace(':', '')
if '/' in comicdir:
comicdir = comicdir.replace('/', '-')
if ',' in comicdir:
comicdir = comicdir.replace(',', '')
else: comicdir = u_comicname
series = comicdir
publisher = ComicPublisher
year = ComicYear
#do work to generate folder path
values = {'$Series': series,
'$Publisher': publisher,
'$Year': year,
'$series': series.lower(),
'$publisher': publisher.lower(),
'$Volume': year
}
if mylar.CONFIG.FOLDER_FORMAT == '':
comlocation = mylar.CONFIG.DESTINATION_DIR + "/" + comicdir + " (" + comic['ComicYear'] + ")"
else:
comlocation = mylar.CONFIG.DESTINATION_DIR + "/" + helpers.replace_all(mylar.CONFIG.FOLDER_FORMAT, values)
#comlocation = mylar.CONFIG.DESTINATION_DIR + "/" + comicdir + " (" + ComicYear + ")"
if mylar.CONFIG.DESTINATION_DIR == "":
logger.error(u"There is no general directory specified - please specify in Config/Post-Processing.")
return
if mylar.CONFIG.REPLACE_SPACES:
#mylar.CONFIG.REPLACE_CHAR ...determines what to replace spaces with underscore or dot
comlocation = comlocation.replace(' ', mylar.CONFIG.REPLACE_CHAR)
#if it doesn't exist - create it (otherwise will bugger up later on)
if os.path.isdir(comlocation):
logger.info(u"Directory (" + comlocation + ") already exists! Continuing...")
else:
if mylar.CONFIG.CREATE_FOLDERS is True:
checkdirectory = filechecker.validateAndCreateDirectory(comlocation, True)
if not checkdirectory:
logger.warn('Error trying to validate/create directory. Aborting this process at this time.')
return
comicIssues = gcdinfo['totalissues']
#let's download the image...
if os.path.exists(mylar.CONFIG.CACHE_DIR): pass
else:
#let's make the dir.
try:
os.makedirs(str(mylar.CONFIG.CACHE_DIR))
logger.info(u"Cache Directory successfully created at: " + str(mylar.CONFIG.CACHE_DIR))
except OSError:
logger.error(u"Could not create cache dir : " + str(mylar.CONFIG.CACHE_DIR))
coverfile = os.path.join(mylar.CONFIG.CACHE_DIR, str(gcomicid) + ".jpg")
#new CV API restriction - one api request / second.
if mylar.CONFIG.CVAPI_RATE is None or mylar.CONFIG.CVAPI_RATE < 2:
time.sleep(2)
else:
time.sleep(mylar.CONFIG.CVAPI_RATE)
urllib.urlretrieve(str(ComicImage), str(coverfile))
try:
with open(str(coverfile)) as f:
ComicImage = os.path.join('cache', str(gcomicid) + ".jpg")
#this is for Firefox when outside the LAN...it works, but I don't know how to implement it
#without breaking the normal flow for inside the LAN (above)
#ComicImage = "http://" + str(mylar.CONFIG.HTTP_HOST) + ":" + str(mylar.CONFIG.HTTP_PORT) + "/cache/" + str(comi$
logger.info(u"Sucessfully retrieved cover for " + ComicName)
#if the comic cover local is checked, save a cover.jpg to the series folder.
if mylar.CONFIG.COMIC_COVER_LOCAL and os.path.isdir(comlocation):
comiclocal = os.path.join(comlocation + "/cover.jpg")
shutil.copy(ComicImage, comiclocal)
except IOError as e:
logger.error(u"Unable to save cover locally at this time.")
#if comic['ComicVersion'].isdigit():
# comicVol = "v" + comic['ComicVersion']
#else:
# comicVol = None
controlValueDict = {"ComicID": gcomicid}
newValueDict = {"ComicName": ComicName,
"ComicSortName": sortname,
"ComicYear": ComicYear,
"Total": comicIssues,
"ComicLocation": comlocation,
#"ComicVersion": comicVol,
"ComicImage": ComicImage,
"ComicImageURL": comic.get('ComicImage', ''),
"ComicImageALTURL": comic.get('ComicImageALT', ''),
#"ComicPublisher": comic['ComicPublisher'],
#"ComicPublished": comicPublished,
"DateAdded": helpers.today(),
"Status": "Loading"}
myDB.upsert("comics", newValueDict, controlValueDict)
#comicsort here...
#run the re-sortorder here in order to properly display the page
if pullupd is None:
helpers.ComicSort(sequence='update')
logger.info(u"Sucessfully retrieved issue details for " + ComicName)
n = 0
iscnt = int(comicIssues)
issnum = []
issname = []
issdate = []
int_issnum = []
#let's start issue #'s at 0 -- thanks to DC for the new 52 reboot! :)
latestiss = "0"
latestdate = "0000-00-00"
#print ("total issues:" + str(iscnt))
#---removed NEW code here---
logger.info(u"Now adding/updating issues for " + ComicName)
bb = 0
while (bb <= iscnt):
#---NEW.code
try:
gcdval = gcdinfo['gcdchoice'][bb]
#print ("gcdval: " + str(gcdval))
except IndexError:
#account for gcd variation here
if gcdinfo['gcdvariation'] == 'gcd':
#print ("gcd-variation accounted for.")
issdate = '0000-00-00'
int_issnum = int (issis / 1000)
break
if 'nn' in str(gcdval['GCDIssue']):
#no number detected - GN, TP or the like
logger.warn(u"Non Series detected (Graphic Novel, etc) - cannot proceed at this time.")
updater.no_searchresults(comicid)
return
elif '.' in str(gcdval['GCDIssue']):
issst = str(gcdval['GCDIssue']).find('.')
issb4dec = str(gcdval['GCDIssue'])[:issst]
#if the length of decimal is only 1 digit, assume it's a tenth
decis = str(gcdval['GCDIssue'])[issst +1:]
if len(decis) == 1:
decisval = int(decis) * 10
issaftdec = str(decisval)
if len(decis) == 2:
decisval = int(decis)
issaftdec = str(decisval)
if int(issaftdec) == 0: issaftdec = "00"
gcd_issue = issb4dec + "." + issaftdec
gcdis = (int(issb4dec) * 1000) + decisval
else:
gcdis = int(str(gcdval['GCDIssue'])) * 1000
gcd_issue = str(gcdval['GCDIssue'])
#get the latest issue / date using the date.
int_issnum = int(gcdis / 1000)
issdate = str(gcdval['GCDDate'])
issid = "G" + str(gcdval['IssueID'])
if gcdval['GCDDate'] > latestdate:
latestiss = str(gcd_issue)
latestdate = str(gcdval['GCDDate'])
#print("(" + str(bb) + ") IssueID: " + str(issid) + " IssueNo: " + str(gcd_issue) + " Date" + str(issdate) )
#---END.NEW.
# check if the issue already exists
iss_exists = myDB.selectone('SELECT * from issues WHERE IssueID=?', [issid]).fetchone()
# Only change the status & add DateAdded if the issue is not already in the database
if iss_exists is None:
newValueDict['DateAdded'] = helpers.today()
#adjust for inconsistencies in GCD date format - some dates have ? which borks up things.
if "?" in str(issdate):
issdate = "0000-00-00"
controlValueDict = {"IssueID": issid}
newValueDict = {"ComicID": gcomicid,
"ComicName": ComicName,
"Issue_Number": gcd_issue,
"IssueDate": issdate,
"Int_IssueNumber": int_issnum
}
#print ("issueid:" + str(controlValueDict))
#print ("values:" + str(newValueDict))
if mylar.CONFIG.AUTOWANT_ALL:
newValueDict['Status'] = "Wanted"
elif issdate > helpers.today() and mylar.CONFIG.AUTOWANT_UPCOMING:
newValueDict['Status'] = "Wanted"
else:
newValueDict['Status'] = "Skipped"
if iss_exists:
#print ("Existing status : " + str(iss_exists['Status']))
newValueDict['Status'] = iss_exists['Status']
myDB.upsert("issues", newValueDict, controlValueDict)
bb+=1
# logger.debug(u"Updating comic cache for " + ComicName)
# cache.getThumb(ComicID=issue['issueid'])
# logger.debug(u"Updating cache for: " + ComicName)
# cache.getThumb(ComicIDcomicid)
controlValueStat = {"ComicID": gcomicid}
newValueStat = {"Status": "Active",
"LatestIssue": latestiss,
"LatestDate": latestdate,
"LastUpdated": helpers.now()
}
myDB.upsert("comics", newValueStat, controlValueStat)
if mylar.CONFIG.CVINFO and os.path.isdir(comlocation):
if not os.path.exists(comlocation + "/cvinfo"):
with open(comlocation + "/cvinfo", "w") as text_file:
text_file.write("http://comicvine.gamespot.com/volume/49-" + str(comicid))
logger.info(u"Updating complete for: " + ComicName)
#move the files...if imported is not empty (meaning it's not from the mass importer.)
if imported is None or imported == 'None':
pass
else:
if mylar.CONFIG.IMP_MOVE:
logger.info("Mass import - Move files")
moveit.movefiles(gcomicid, comlocation, ogcname)
else:
logger.info("Mass import - Moving not Enabled. Setting Archived Status for import.")
moveit.archivefiles(gcomicid, ogcname)
#check for existing files...
updater.forceRescan(gcomicid)
if pullupd is None:
# lets' check the pullist for anyting at this time as well since we're here.
if mylar.CONFIG.AUTOWANT_UPCOMING and 'Present' in ComicPublished:
logger.info(u"Checking this week's pullist for new issues of " + ComicName)
updater.newpullcheck(comic['ComicName'], gcomicid)
#here we grab issues that have been marked as wanted above...
results = myDB.select("SELECT * FROM issues where ComicID=? AND Status='Wanted'", [gcomicid])
if results:
logger.info(u"Attempting to grab wanted issues for : " + ComicName)
for result in results:
foundNZB = "none"
if (mylar.CONFIG.NZBSU or mylar.CONFIG.DOGNZB or mylar.CONFIG.EXPERIMENTAL or mylar.CONFIG.NEWZNAB) and (mylar.CONFIG.SAB_HOST):
foundNZB = search.searchforissue(result['IssueID'])
if foundNZB == "yes":
updater.foundsearch(result['ComicID'], result['IssueID'])
else: logger.info(u"No issues marked as wanted for " + ComicName)
logger.info(u"Finished grabbing what I could.")
def issue_collection(issuedata, nostatus):
myDB = db.DBConnection()
nowdate = datetime.datetime.now()
now_week = datetime.datetime.strftime(nowdate, "%Y%U")
if issuedata:
for issue in issuedata:
controlValueDict = {"IssueID": issue['IssueID']}
newValueDict = {"ComicID": issue['ComicID'],
"ComicName": issue['ComicName'],
"IssueName": issue['IssueName'],
"Issue_Number": issue['Issue_Number'],
"IssueDate": issue['IssueDate'],
"ReleaseDate": issue['ReleaseDate'],
"DigitalDate": issue['DigitalDate'],
"Int_IssueNumber": issue['Int_IssueNumber'],
"ImageURL": issue['ImageURL'],
"ImageURL_ALT": issue['ImageURL_ALT']
#"Status": "Skipped" #set this to Skipped by default to avoid NULL entries.
}
# check if the issue already exists
iss_exists = myDB.selectone('SELECT * from issues WHERE IssueID=?', [issue['IssueID']]).fetchone()
dbwrite = "issues"
#if iss_exists is None:
# iss_exists = myDB.selectone('SELECT * from annuals WHERE IssueID=?', [issue['IssueID']]).fetchone()
# if iss_exists:
# dbwrite = "annuals"
if nostatus == 'False':
# Only change the status & add DateAdded if the issue is already in the database
if iss_exists is None:
newValueDict['DateAdded'] = helpers.today()
if issue['ReleaseDate'] == '0000-00-00':
dk = re.sub('-', '', issue['IssueDate']).strip()
else:
dk = re.sub('-', '', issue['ReleaseDate']).strip() # converts date to 20140718 format
if dk == '00000000':
logger.warn('Issue Data is invalid for Issue Number %s. Marking this issue as Skipped' % issue['Issue_Number'])
newValueDict['Status'] = "Skipped"
else:
datechk = datetime.datetime.strptime(dk, "%Y%m%d")
issue_week = datetime.datetime.strftime(datechk, "%Y%U")
if mylar.CONFIG.AUTOWANT_ALL:
newValueDict['Status'] = "Wanted"
#logger.fdebug('autowant all')
elif issue_week >= now_week and mylar.CONFIG.AUTOWANT_UPCOMING:
#logger.fdebug(str(datechk) + ' >= ' + str(nowtime))
newValueDict['Status'] = "Wanted"
else:
newValueDict['Status'] = "Skipped"
#logger.fdebug('status is : ' + str(newValueDict))
else:
#logger.fdebug('Existing status for issue #%s : %s' % (issue['Issue_Number'], iss_exists['Status']))
if any([iss_exists['Status'] is None, iss_exists['Status'] == 'None']):
is_status = 'Skipped'
else:
is_status = iss_exists['Status']
newValueDict['Status'] = is_status
else:
#logger.fdebug("Not changing the status at this time - reverting to previous module after to re-append existing status")
pass #newValueDict['Status'] = "Skipped"
try:
myDB.upsert(dbwrite, newValueDict, controlValueDict)
except sqlite3.InterfaceError, e:
#raise sqlite3.InterfaceError(e)
logger.error('Something went wrong - I cannot add the issue information into my DB.')
myDB.action("DELETE FROM comics WHERE ComicID=?", [issue['ComicID']])
return
def manualAnnual(manual_comicid=None, comicname=None, comicyear=None, comicid=None, annchk=None, manualupd=False):
#called when importing/refreshing an annual that was manually added.
myDB = db.DBConnection()
if annchk is None:
nowdate = datetime.datetime.now()
now_week = datetime.datetime.strftime(nowdate, "%Y%U")
annchk = []
issueid = manual_comicid
logger.fdebug(str(issueid) + ' added to series list as an Annual')
sr = cv.getComic(manual_comicid, 'comic')
logger.fdebug('Attempting to integrate ' + sr['ComicName'] + ' (' + str(issueid) + ') to the existing series of ' + comicname + '(' + str(comicyear) + ')')
if len(sr) is None or len(sr) == 0:
logger.fdebug('Could not find any information on the series indicated : ' + str(manual_comicid))
return
else:
n = 0
issued = cv.getComic(re.sub('4050-', '', manual_comicid).strip(), 'issue')
if int(sr['ComicIssues']) == 0 and len(issued['issuechoice']) == 1:
noissues = 1
else:
noissues = sr['ComicIssues']
logger.fdebug('there are ' + str(noissues) + ' annuals within this series.')
while (n < int(noissues)):
try:
firstval = issued['issuechoice'][n]
except IndexError:
break
try:
cleanname = helpers.cleanName(firstval['Issue_Name'])
except:
cleanname = 'None'
if firstval['Store_Date'] == '0000-00-00':
dk = re.sub('-', '', firstval['Issue_Date']).strip()
else:
dk = re.sub('-', '', firstval['Store_Date']).strip() # converts date to 20140718 format
if dk == '00000000':
logger.warn('Issue Data is invalid for Issue Number %s. Marking this issue as Skipped' % firstval['Issue_Number'])
astatus = "Skipped"
else:
datechk = datetime.datetime.strptime(dk, "%Y%m%d")
issue_week = datetime.datetime.strftime(datechk, "%Y%U")
if mylar.CONFIG.AUTOWANT_ALL:
astatus = "Wanted"
elif issue_week >= now_week and mylar.CONFIG.AUTOWANT_UPCOMING is True:
astatus = "Wanted"
else:
astatus = "Skipped"
annchk.append({'IssueID': str(firstval['Issue_ID']),
'ComicID': comicid,
'ReleaseComicID': re.sub('4050-', '', manual_comicid).strip(),
'ComicName': comicname,
'Issue_Number': str(firstval['Issue_Number']),
'IssueName': cleanname,
'IssueDate': str(firstval['Issue_Date']),
'ReleaseDate': str(firstval['Store_Date']),
'DigitalDate': str(firstval['Digital_Date']),
'Status': astatus,
'ReleaseComicName': sr['ComicName']})
n+=1
if manualupd is True:
return annchk
for ann in annchk:
newCtrl = {"IssueID": ann['IssueID']}
newVals = {"Issue_Number": ann['Issue_Number'],
"Int_IssueNumber": helpers.issuedigits(ann['Issue_Number']),
"IssueDate": ann['IssueDate'],
"ReleaseDate": ann['ReleaseDate'],
"DigitalDate": ann['DigitalDate'],
"IssueName": ann['IssueName'],
"ComicID": ann['ComicID'], #this is the series ID
"ReleaseComicID": ann['ReleaseComicID'], #this is the series ID for the annual(s)
"ComicName": ann['ComicName'], #series ComicName
"ReleaseComicName": ann['ReleaseComicName'], #series ComicName for the manual_comicid
"Status": ann['Status']}
#need to add in the values for the new series to be added.
#"M_ComicName": sr['ComicName'],
#"M_ComicID": manual_comicid}
myDB.upsert("annuals", newVals, newCtrl)
if len(annchk) > 0:
logger.info('Successfully integrated ' + str(len(annchk)) + ' annuals into the series: ' + annchk[0]['ComicName'])
return
def updateissuedata(comicid, comicname=None, issued=None, comicIssues=None, calledfrom=None, issuechk=None, issuetype=None, SeriesYear=None, latestissueinfo=None):
annualchk = []
weeklyissue_check = []
logger.fdebug('issuedata call references...')
logger.fdebug('comicid: %s' % comicid)
logger.fdebug('comicname: %s' % comicname)
logger.fdebug('comicissues: %s' % comicIssues)
logger.fdebug('calledfrom: %s' % calledfrom)
logger.fdebug('issuechk: %s' % issuechk)
logger.fdebug('latestissueinfo: %s' % latestissueinfo)
logger.fdebug('issuetype: %s' % issuetype)
#to facilitate independent calls to updateissuedata ONLY, account for data not available and get it.
#chkType comes from the weeklypulllist - either 'annual' or not to distinguish annuals vs. issues
if comicIssues is None:
comic = cv.getComic(comicid, 'comic')
if comic is None:
logger.warn('Error retrieving from ComicVine - either the site is down or you are not using your own CV API key')
return
if comicIssues is None:
comicIssues = comic['ComicIssues']
if SeriesYear is None:
SeriesYear = comic['ComicYear']
if comicname is None:
comicname = comic['ComicName']
if issued is None:
issued = cv.getComic(comicid, 'issue')
if issued is None:
logger.warn('Error retrieving from ComicVine - either the site is down or you are not using your own CV API key')
return
# poll against annuals here - to make sure annuals are uptodate.
annualchk = annual_check(comicname, SeriesYear, comicid, issuetype, issuechk, annualchk)
if annualchk is None:
annualchk = []
logger.fdebug('Finished Annual checking.')
n = 0
iscnt = int(comicIssues)
issid = []
issnum = []
issname = []
issdate = []
issuedata = []
#let's start issue #'s at 0 -- thanks to DC for the new 52 reboot! :)
latestiss = "0"
latestdate = "0000-00-00"
latest_stdate = "0000-00-00"
latestissueid = None
firstiss = "10000000"
firstdate = "2099-00-00"
#print ("total issues:" + str(iscnt))
logger.info('Now adding/updating issues for ' + comicname)
if iscnt > 0: #if a series is brand new, it wont have any issues/details yet so skip this part
while (n <= iscnt):
try:
firstval = issued['issuechoice'][n]
except IndexError:
break
try:
cleanname = helpers.cleanName(firstval['Issue_Name'])
except:
cleanname = 'None'
issid = str(firstval['Issue_ID'])
issnum = firstval['Issue_Number']
issname = cleanname
issdate = str(firstval['Issue_Date'])
storedate = str(firstval['Store_Date'])
digitaldate = str(firstval['Digital_Date'])
int_issnum = None
if issnum.isdigit():
int_issnum = int(issnum) * 1000
else:
if 'a.i.' in issnum.lower() or 'ai' in issnum.lower():
issnum = re.sub('\.', '', issnum)
#int_issnum = (int(issnum[:-2]) * 1000) + ord('a') + ord('i')
if 'au' in issnum.lower():
int_issnum = (int(issnum[:-2]) * 1000) + ord('a') + ord('u')
elif 'inh' in issnum.lower():
int_issnum = (int(issnum[:-4]) * 1000) + ord('i') + ord('n') + ord('h')
elif 'now' in issnum.lower():
int_issnum = (int(issnum[:-4]) * 1000) + ord('n') + ord('o') + ord('w')
elif 'mu' in issnum.lower():
int_issnum = (int(issnum[:-3]) * 1000) + ord('m') + ord('u')
elif 'hu' in issnum.lower():
int_issnum = (int(issnum[:-3]) * 1000) + ord('h') + ord('u')
elif u'\xbd' in issnum:
tmpiss = re.sub('[^0-9]', '', issnum).strip()
if len(tmpiss) > 0:
int_issnum = (int(tmpiss) + .5) * 1000
else:
int_issnum = .5 * 1000
logger.fdebug('1/2 issue detected :' + issnum + ' === ' + str(int_issnum))
elif u'\xbc' in issnum:
int_issnum = .25 * 1000
elif u'\xbe' in issnum:
int_issnum = .75 * 1000
elif u'\u221e' in issnum:
#issnum = utf-8 will encode the infinity symbol without any help
int_issnum = 9999999999 * 1000 # set 9999999999 for integer value of issue
elif '.' in issnum or ',' in issnum:
if ',' in issnum: issnum = re.sub(',', '.', issnum)
issst = str(issnum).find('.')
#logger.fdebug("issst:" + str(issst))
if issst == 0:
issb4dec = 0
else:
issb4dec = str(issnum)[:issst]
#logger.fdebug("issb4dec:" + str(issb4dec))
#if the length of decimal is only 1 digit, assume it's a tenth
decis = str(issnum)[issst +1:]
#logger.fdebug("decis:" + str(decis))
if len(decis) == 1:
decisval = int(decis) * 10
issaftdec = str(decisval)
elif len(decis) == 2:
decisval = int(decis)
issaftdec = str(decisval)
else:
decisval = decis
issaftdec = str(decisval)
#if there's a trailing decimal (ie. 1.50.) and it's either intentional or not, blow it away.
if issaftdec[-1:] == '.':
logger.fdebug('Trailing decimal located within issue number. Irrelevant to numbering. Obliterating.')
issaftdec = issaftdec[:-1]
try:
# int_issnum = str(issnum)
int_issnum = (int(issb4dec) * 1000) + (int(issaftdec) * 10)
except ValueError:
logger.error('This has no issue # for me to get - Either a Graphic Novel or one-shot.')
updater.no_searchresults(comicid)
return
else:
try:
x = float(issnum)
#validity check
if x < 0:
logger.fdebug('I have encountered a negative issue #: ' + str(issnum) + '. Trying to accomodate.')
logger.fdebug('value of x is : ' + str(x))
int_issnum = (int(x) *1000) - 1
else: raise ValueError
except ValueError, e:
x = 0
tstord = None
issno = None
invchk = "false"
if issnum.lower() != 'preview':
while (x < len(issnum)):
if issnum[x].isalpha():
#take first occurance of alpha in string and carry it through
tstord = issnum[x:].rstrip()
tstord = re.sub('[\-\,\.\+]', '', tstord).rstrip()
issno = issnum[:x].rstrip()
issno = re.sub('[\-\,\.\+]', '', issno).rstrip()
try:
isschk = float(issno)
except ValueError, e:
if len(issnum) == 1 and issnum.isalpha():
logger.fdebug('detected lone alpha issue. Attempting to figure this out.')
break
logger.fdebug('[' + issno + '] invalid numeric for issue - cannot be found. Ignoring.')
issno = None
tstord = None
invchk = "true"
break
x+=1
if all([tstord is not None, issno is not None, int_issnum is None]):
a = 0
ordtot = 0
if len(issnum) == 1 and issnum.isalpha():
int_issnum = ord(tstord.lower())
else:
while (a < len(tstord)):
ordtot += ord(tstord[a].lower()) #lower-case the letters for simplicty
a+=1
int_issnum = (int(issno) * 1000) + ordtot
elif invchk == "true":
if any([issnum.lower() == 'fall 2005', issnum.lower() == 'spring 2005', issnum.lower() == 'summer 2006', issnum.lower() == 'winter 2009']):
issnum = re.sub('[0-9]+', '', issnum).strip()
inu = 0
ordtot = 0
while (inu < len(issnum)):
ordtot += ord(issnum[inu].lower()) #lower-case the letters for simplicty
inu+=1
int_issnum = ordtot
else:
logger.fdebug('this does not have an issue # that I can parse properly.')
return
else:
if int_issnum is not None:
pass
elif issnum == '9-5':
issnum = u'9\xbd'
logger.fdebug('issue: 9-5 is an invalid entry. Correcting to : ' + issnum)
int_issnum = (9 * 1000) + (.5 * 1000)
elif issnum == '112/113':
int_issnum = (112 * 1000) + (.5 * 1000)
elif issnum == '14-16':
int_issnum = (15 * 1000) + (.5 * 1000)
elif issnum.lower() == 'preview':
inu = 0
ordtot = 0
while (inu < len(issnum)):
ordtot += ord(issnum[inu].lower()) #lower-case the letters for simplicty
inu+=1
int_issnum = ordtot
else:
logger.error(issnum + ' this has an alpha-numeric in the issue # which I cannot account for.')
return
#get the latest issue / date using the date.
#logger.fdebug('issue : ' + str(issnum))
#logger.fdebug('latest date: ' + str(latestdate))
#logger.fdebug('first date: ' + str(firstdate))
#logger.fdebug('issue date: ' + str(firstval['Issue_Date']))
#logger.fdebug('issue date: ' + storedate)
if any([firstval['Issue_Date'] >= latestdate, storedate >= latestdate]):
#logger.fdebug('date check hit for issue date > latestdate')
if int_issnum > helpers.issuedigits(latestiss):
#logger.fdebug('assigning latest issue to : ' + str(issnum))
latestiss = issnum
latestissueid = issid
if firstval['Issue_Date'] != '0000-00-00':
latestdate = str(firstval['Issue_Date'])
latest_stdate = storedate
else:
latestdate = storedate
latest_stdate = storedate
if firstval['Issue_Date'] < firstdate and firstval['Issue_Date'] != '0000-00-00':
firstiss = issnum
firstdate = str(firstval['Issue_Date'])
if issuechk is not None and issuetype == 'series':
logger.fdebug('comparing ' + str(issuechk) + ' .. to .. ' + str(int_issnum))
if issuechk == int_issnum:
weeklyissue_check.append({"Int_IssueNumber": int_issnum,
"Issue_Number": issnum,
"IssueDate": issdate,
"ReleaseDate": storedate,
"ComicID": comicid,
"IssueID": issid})
issuedata.append({"ComicID": comicid,
"IssueID": issid,
"ComicName": comicname,
"IssueName": issname,
"Issue_Number": issnum,
"IssueDate": issdate,
"ReleaseDate": storedate,
"DigitalDate": digitaldate,
"Int_IssueNumber": int_issnum,
"ImageURL": firstval['Image'],
"ImageURL_ALT": firstval['ImageALT']})
n+=1
if calledfrom == 'futurecheck' and len(issuedata) == 0:
logger.fdebug('This is a NEW series with no issue data - skipping issue updating for now, and assigning generic information so things don\'t break')
latestdate = latestissueinfo[0]['latestdate'] # if it's from futurecheck, issuechk holds the latestdate for the given issue
latestiss = latestissueinfo[0]['latestiss']
lastpubdate = 'Present'
publishfigure = str(SeriesYear) + ' - ' + str(lastpubdate)
else:
#if calledfrom == 'weeklycheck':
if len(issuedata) >= 1 and not calledfrom == 'dbupdate':
logger.fdebug('initiating issue updating - info & status')
issue_collection(issuedata, nostatus='False')
else:
logger.fdebug('initiating issue updating - just the info')
issue_collection(issuedata, nostatus='True')
styear = str(SeriesYear)
if firstdate is not None:
if SeriesYear != firstdate[:4]:
if firstdate[:4] == '2099':
logger.fdebug('Series start date (%s) differs from First Issue start date as First Issue date is unknown - assuming Series Year as Start Year (even though CV might say previous year - it\'s all gravy).' % (SeriesYear))
else:
logger.fdebug('Series start date (%s) cannot be properly determined and/or it might cross over into different year (%s) - assuming store date of first issue (%s) as Start Year (even though CV might say previous year - it\'s all gravy).' % (SeriesYear, firstdate[:4], firstdate))
if firstdate == '2099-00-00':
firstdate = '%s-01-01' % SeriesYear
styear = str(firstdate[:4])
if firstdate[5:7] == '00':
stmonth = "?"
else:
stmonth = helpers.fullmonth(firstdate[5:7])
ltyear = re.sub('/s', '', latestdate[:4])
if latestdate[5:7] == '00':
ltmonth = "?"
else:
ltmonth = helpers.fullmonth(latestdate[5:7])
#try to determine if it's an 'actively' published comic from above dates
#threshold is if it's within a month (<55 days) let's assume it's recent.
try:
c_date = datetime.date(int(latestdate[:4]), int(latestdate[5:7]), 1)
except:
logger.error('Cannot determine Latest Date for given series. This is most likely due to an issue having a date of : 0000-00-00')
latestdate = str(SeriesYear) + '-01-01'
logger.error('Setting Latest Date to be ' + str(latestdate) + '. You should inform CV that the issue data is stale.')
c_date = datetime.date(int(latestdate[:4]), int(latestdate[5:7]), 1)
n_date = datetime.date.today()
recentchk = (n_date - c_date).days
if recentchk <= 55:
lastpubdate = 'Present'
else:
if ltmonth == '?':
if ltyear == '0000':
lastpubdate = '?'
else:
lastpubdate = str(ltyear)
elif ltyear == '0000':
lastpubdate = '?'
else:
lastpubdate = str(ltmonth) + ' ' + str(ltyear)
if stmonth == '?' and ('?' in lastpubdate and '0000' in lastpubdate):
lastpubdate = 'Present'
newpublish = True
publishfigure = str(styear) + ' - ' + str(lastpubdate)
else:
newpublish = False
publishfigure = str(stmonth) + ' ' + str(styear) + ' - ' + str(lastpubdate)
if stmonth == '?' and styear == '?' and lastpubdate =='0000' and comicIssues == '0':
logger.info('No available issue data - I believe this is a NEW series.')
latestdate = latestissueinfo[0]['latestdate']
latestiss = latestissueinfo[0]['latestiss']
lastpubdate = 'Present'
publishfigure = str(SeriesYear) + ' - ' + str(lastpubdate)
controlValueStat = {"ComicID": comicid}
newValueStat = {"Status": "Active",
"Total": comicIssues,
"ComicPublished": publishfigure,
"NewPublish": newpublish,
"LatestIssue": latestiss,
"LatestIssueID": latestissueid,
"LatestDate": latestdate,
"LastUpdated": helpers.now()
}
myDB = db.DBConnection()
myDB.upsert("comics", newValueStat, controlValueStat)
importantdates = {}
importantdates['LatestIssue'] = latestiss
importantdates['LatestIssueID'] = latestissueid
importantdates['LatestDate'] = latestdate
importantdates['LatestStoreDate'] = latest_stdate
importantdates['LastPubDate'] = lastpubdate
importantdates['SeriesStatus'] = 'Active'
if calledfrom == 'weeklycheck':
return weeklyissue_check
elif len(issuedata) >= 1 and not calledfrom == 'dbupdate':
return {'issuedata': issuedata,
'annualchk': annualchk,
'importantdates': importantdates,
'nostatus': False}
elif calledfrom == 'dbupdate':
return {'issuedata': issuedata,
'annualchk': annualchk,
'importantdates': importantdates,
'nostatus': True}
else:
return importantdates
def annual_check(ComicName, SeriesYear, comicid, issuetype, issuechk, annualslist):
annualids = [] #to be used to make sure an ID isn't double-loaded
annload = []
anncnt = 0
nowdate = datetime.datetime.now()
now_week = datetime.datetime.strftime(nowdate, "%Y%U")
myDB = db.DBConnection()
annual_load = myDB.select('SELECT * FROM annuals WHERE ComicID=?', [comicid])
logger.fdebug('checking annual db')
for annthis in annual_load:
if not any(d['ReleaseComicID'] == annthis['ReleaseComicID'] for d in annload):
#print 'matched on annual'
annload.append({
'ReleaseComicID': annthis['ReleaseComicID'],
'ReleaseComicName': annthis['ReleaseComicName'],
'ComicID': annthis['ComicID'],
'ComicName': annthis['ComicName']
})
if annload is None:
pass
else:
for manchk in annload:
if manchk['ReleaseComicID'] is not None or manchk['ReleaseComicID'] is not None: #if it exists, then it's a pre-existing add
#print str(manchk['ReleaseComicID']), comic['ComicName'], str(SeriesYear), str(comicid)
annualslist += manualAnnual(manchk['ReleaseComicID'], ComicName, SeriesYear, comicid, manualupd=True)
annualids.append(manchk['ReleaseComicID'])
annualcomicname = re.sub('[\,\:]', '', ComicName)
if annualcomicname.lower().startswith('the'):
annComicName = annualcomicname[4:] + ' annual'
else:
annComicName = annualcomicname + ' annual'
mode = 'series'
annualyear = SeriesYear # no matter what, the year won't be less than this.
logger.fdebug('[IMPORTER-ANNUAL] - Annual Year:' + str(annualyear))
sresults = mb.findComic(annComicName, mode, issue=None)
type='comic'
annual_types_ignore = {'paperback', 'collecting', 'reprints', 'collected edition', 'print edition', 'tpb', 'available in print', 'collects'}
if len(sresults) > 0:
logger.fdebug('[IMPORTER-ANNUAL] - there are ' + str(len(sresults)) + ' results.')
num_res = 0
while (num_res < len(sresults)):
sr = sresults[num_res]
#logger.fdebug("description:" + sr['description'])
for x in annual_types_ignore:
if x in sr['description'].lower():
test_id_position = sr['description'].find(comicid)
if test_id_position >= sr['description'].lower().find(x) or test_id_position == -1:
logger.fdebug('[IMPORTER-ANNUAL] - tradeback/collected edition detected - skipping ' + str(sr['comicid']))
continue
if comicid in sr['description']:
logger.fdebug('[IMPORTER-ANNUAL] - ' + str(comicid) + ' found. Assuming it is part of the greater collection.')
issueid = sr['comicid']
logger.fdebug('[IMPORTER-ANNUAL] - ' + str(issueid) + ' added to series list as an Annual')
if issueid in annualids:
logger.fdebug('[IMPORTER-ANNUAL] - ' + str(issueid) + ' already exists within current annual list for series.')
num_res+=1 # need to manually increment since not a for-next loop
continue
issued = cv.getComic(issueid, 'issue')
if len(issued) is None or len(issued) == 0:
logger.fdebug('[IMPORTER-ANNUAL] - Could not find any annual information...')
pass
else:
n = 0
if int(sr['issues']) == 0 and len(issued['issuechoice']) == 1:
sr_issues = 1
else:
if int(sr['issues']) != len(issued['issuechoice']):
sr_issues = len(issued['issuechoice'])
else:
sr_issues = sr['issues']
logger.fdebug('[IMPORTER-ANNUAL] - There are ' + str(sr_issues) + ' annuals in this series.')
while (n < int(sr_issues)):
try:
firstval = issued['issuechoice'][n]
except IndexError:
break
try:
cleanname = helpers.cleanName(firstval['Issue_Name'])
except:
cleanname = 'None'
issid = str(firstval['Issue_ID'])
issnum = str(firstval['Issue_Number'])
issname = cleanname
issdate = str(firstval['Issue_Date'])
stdate = str(firstval['Store_Date'])
digdate = str(firstval['Digital_Date'])
int_issnum = helpers.issuedigits(issnum)
iss_exists = myDB.selectone('SELECT * from annuals WHERE IssueID=?', [issid]).fetchone()
if iss_exists is None:
if stdate == '0000-00-00':
dk = re.sub('-', '', issdate).strip()
else:
dk = re.sub('-', '', stdate).strip() # converts date to 20140718 format
if dk == '00000000':
logger.warn('Issue Data is invalid for Issue Number %s. Marking this issue as Skipped' % firstval['Issue_Number'])
astatus = "Skipped"
else:
datechk = datetime.datetime.strptime(dk, "%Y%m%d")
issue_week = datetime.datetime.strftime(datechk, "%Y%U")
if mylar.CONFIG.AUTOWANT_ALL:
astatus = "Wanted"
elif issue_week >= now_week and mylar.CONFIG.AUTOWANT_UPCOMING is True:
astatus = "Wanted"
else:
astatus = "Skipped"
else:
astatus = iss_exists['Status']
annualslist.append({"Issue_Number": issnum,
"Int_IssueNumber": int_issnum,
"IssueDate": issdate,
"ReleaseDate": stdate,
"DigitalDate": digdate,
"IssueName": issname,
"ComicID": comicid,
"IssueID": issid,
"ComicName": ComicName,
"ReleaseComicID": re.sub('4050-', '', firstval['Comic_ID']).strip(),
"ReleaseComicName": sr['name'],
"Status": astatus})
#myDB.upsert("annuals", newVals, newCtrl)
# --- don't think this does anything since the value isn't returned in this module
#if issuechk is not None and issuetype == 'annual':
# #logger.fdebug('[IMPORTER-ANNUAL] - Comparing annual ' + str(issuechk) + ' .. to .. ' + str(int_issnum))
# if issuechk == int_issnum:
# weeklyissue_check.append({"Int_IssueNumber": int_issnum,
# "Issue_Number": issnum,
# "IssueDate": issdate,
# "ReleaseDate": stdate})
n+=1
num_res+=1
manualAnnual(annchk=annualslist)
return annualslist
elif len(sresults) == 0 or len(sresults) is None:
logger.fdebug('[IMPORTER-ANNUAL] - No results, removing the year from the agenda and re-querying.')
sresults = mb.findComic(annComicName, mode, issue=None)
if len(sresults) == 1:
sr = sresults[0]
logger.fdebug('[IMPORTER-ANNUAL] - ' + str(comicid) + ' found. Assuming it is part of the greater collection.')
else:
resultset = 0
else:
logger.fdebug('[IMPORTER-ANNUAL] - Returning results to screen - more than one possibility')
for sr in sresults:
if annualyear < sr['comicyear']:
logger.fdebug('[IMPORTER-ANNUAL] - ' + str(annualyear) + ' is less than ' + str(sr['comicyear']))
if int(sr['issues']) > (2013 - int(sr['comicyear'])):
logger.fdebug('[IMPORTER-ANNUAL] - Issue count is wrong')
#if this is called from the importer module, return the weeklyissue_check
def image_it(comicid, latestissueid, comlocation, ComicImage):
#alternate series covers download latest image...
cimage = os.path.join(mylar.CONFIG.CACHE_DIR, str(comicid) + '.jpg')
imageurl = mylar.cv.getComic(comicid, 'image', issueid=latestissueid)
covercheck = helpers.getImage(comicid, imageurl['image'])
if covercheck == 'retry':
logger.fdebug('Attempting to retrieve a different comic image for this particular issue.')
if imageurl['image_alt'] is not None:
covercheck = helpers.getImage(comicid, imageurl['image_alt'])
else:
if not os.path.isfile(cimage):
logger.fdebug('Failed to retrieve issue image, possibly because not available. Reverting back to series image.')
covercheck = helpers.getImage(comicid, ComicImage)
PRComicImage = os.path.join('cache', str(comicid) + ".jpg")
ComicImage = helpers.replacetheslash(PRComicImage)
#if the comic cover local is checked, save a cover.jpg to the series folder.
if all([mylar.CONFIG.COMIC_COVER_LOCAL is True, os.path.isdir(comlocation) is True, os.path.isfile(os.path.join(comlocation, 'cover.jpg'))]):
try:
comiclocal = os.path.join(comlocation, 'cover.jpg')
shutil.copyfile(cimage, comiclocal)
if mylar.CONFIG.ENFORCE_PERMS:
filechecker.setperms(comiclocal)
except IOError as e:
logger.error('[%s] Error saving cover (%s) into series directory (%s) at this time' % (e, cimage, comiclocal))
except Exception as e:
logger.error('[%s] Unable to save cover (%s) into series directory (%s) at this time' % (e, cimage, comiclocal))
myDB = db.DBConnection()
myDB.upsert('comics', {'ComicImage': ComicImage}, {'ComicID': comicid})
| 80,815 | Python | .py | 1,420 | 41.75 | 298 | 0.542585 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,233 | newpull.py | evilhero_mylar/mylar/newpull.py |
from bs4 import BeautifulSoup, UnicodeDammit
import urllib2
import csv
import fileinput
import sys
import re
import os
import sqlite3
import datetime
import unicodedata
from decimal import Decimal
from HTMLParser import HTMLParseError
from time import strptime
import requests
import mylar
from mylar import logger
def newpull():
pagelinks = "http://www.previewsworld.com/Home/1/1/71/952"
try:
r = requests.get(pagelinks, verify=False)
except Exception, e:
logger.warn('Error fetching data: %s' % e)
soup = BeautifulSoup(r.content)
getthedate = soup.findAll("div", {"class": "Headline"})[0]
#the date will be in the FIRST ahref
try:
getdate_link = getthedate('a')[0]
newdates = getdate_link.findNext(text=True).strip()
except IndexError:
newdates = getthedate.findNext(text=True).strip()
logger.fdebug('New Releases date detected as : ' + re.sub('New Releases For', '', newdates).strip())
cntlinks = soup.findAll('tr')
lenlinks = len(cntlinks)
publish = []
resultURL = []
resultmonth = []
resultyear = []
x = 0
cnt = 0
endthis = False
pull_list = []
publishers = {'PREVIEWS PUBLICATIONS', 'DARK HORSE COMICS', 'DC COMICS', 'IDW PUBLISHING', 'IMAGE COMICS', 'MARVEL COMICS', 'COMICS & GRAPHIC NOVELS', 'MAGAZINES', 'MERCHANDISE'}
isspublisher = None
while (x < lenlinks):
headt = cntlinks[x] #iterate through the hrefs pulling out only results.
found_iss = headt.findAll('td')
pubcheck = found_iss[0].text.strip() #.findNext(text=True)
for pub in publishers:
if pub in pubcheck:
chklink = found_iss[0].findAll('a', href=True) #make sure it doesn't have a link in it.
if not chklink:
isspublisher = pub
break
if isspublisher == 'PREVIEWS PUBLICATIONS' or isspublisher is None:
pass
elif any([isspublisher == 'MAGAZINES', isspublisher == 'MERCHANDISE']):
#logger.fdebug('End.')
endthis = True
break
else:
if "PREVIEWS" in headt:
#logger.fdebug('Ignoring: ' + found_iss[0])
break
if '/Catalog/' in str(headt):
findurl_link = headt.findAll('a', href=True)[0]
urlID = findurl_link.findNext(text=True)
issue_link = findurl_link['href']
issue_lk = issue_link.find('/Catalog/')
if issue_lk == -1:
x+=1
continue
elif "Home/1/1/71" in issue_link:
#logger.fdebug('Ignoring - menu option.')
x+=1
continue
if len(found_iss) > 0:
pull_list.append({"iss_url": issue_link,
"name": found_iss[1].findNext(text=True),
"price": found_iss[2],
"publisher": isspublisher,
"ID": urlID})
x+=1
logger.fdebug('Saving new pull-list information into local file for subsequent merge')
except_file = os.path.join(mylar.CACHE_DIR, 'newreleases.txt')
try:
csvfile = open(str(except_file), 'rb')
csvfile.close()
except (OSError, IOError):
logger.fdebug('file does not exist - continuing.')
else:
logger.fdebug('file exists - removing.')
os.remove(except_file)
oldpub = None
breakhtml = {"<td>", "<tr>", "</td>", "</tr>"}
with open(str(except_file), 'wb') as f:
f.write('%s\n' % (newdates))
for pl in pull_list:
if pl['publisher'] == oldpub:
exceptln = str(pl['ID']) + "\t" + pl['name'].replace(u"\xA0", u" ") + "\t" + str(pl['price'])
else:
exceptln = pl['publisher'] + "\n" + str(pl['ID']) + "\t" + pl['name'].replace(u"\xA0", u" ") + "\t" + str(pl['price'])
for lb in breakhtml:
exceptln = re.sub(lb, '', exceptln).strip()
exceptline = exceptln.decode('utf-8', 'ignore')
f.write('%s\n' % (exceptline.encode('ascii', 'replace').strip()))
oldpub = pl['publisher']
if __name__ == '__main__':
newpull()
| 4,753 | Python | .py | 108 | 30.277778 | 186 | 0.511299 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,234 | mb.py | evilhero_mylar/mylar/mb.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import re
import time
import threading
import platform
import urllib, urllib2
from xml.dom.minidom import parseString, Element
from xml.parsers.expat import ExpatError
import requests
import mylar
from mylar import logger, db, cv
from mylar.helpers import multikeysort, replace_all, cleanName, listLibrary, listStoryArcs
import httplib
mb_lock = threading.Lock()
def patch_http_response_read(func):
def inner(*args):
try:
return func(*args)
except httplib.IncompleteRead, e:
return e.partial
return inner
httplib.HTTPResponse.read = patch_http_response_read(httplib.HTTPResponse.read)
if platform.python_version() == '2.7.6':
httplib.HTTPConnection._http_vsn = 10
httplib.HTTPConnection._http_vsn_str = 'HTTP/1.0'
def pullsearch(comicapi, comicquery, offset, type):
cnt = 1
for x in comicquery:
if cnt == 1:
filterline = '%s' % x
else:
filterline+= ',name:%s' % x
cnt+=1
PULLURL = mylar.CVURL + str(type) + 's?api_key=' + str(comicapi) + '&filter=name:' + filterline + '&field_list=id,name,start_year,site_detail_url,count_of_issues,image,publisher,deck,description,first_issue,last_issue&format=xml&sort=date_last_updated:desc&offset=' + str(offset) # 2012/22/02 - CVAPI flipped back to offset instead of page
#all these imports are standard on most modern python implementations
#logger.info('MB.PULLURL:' + PULLURL)
#new CV API restriction - one api request / second.
if mylar.CONFIG.CVAPI_RATE is None or mylar.CONFIG.CVAPI_RATE < 2:
time.sleep(2)
else:
time.sleep(mylar.CONFIG.CVAPI_RATE)
#download the file:
payload = None
try:
r = requests.get(PULLURL, params=payload, verify=mylar.CONFIG.CV_VERIFY, headers=mylar.CV_HEADERS)
except Exception as e:
logger.warn('Error fetching data from ComicVine: %s' % e)
return
try:
dom = parseString(r.content) #(data)
except ExpatError:
if u'<title>Abnormal Traffic Detected' in r.content:
logger.error('ComicVine has banned this server\'s IP address because it exceeded the API rate limit.')
else:
logger.warn('[WARNING] ComicVine is not responding correctly at the moment. This is usually due to some problems on their end. If you re-try things again in a few moments, it might work properly.')
return
except Exception as e:
logger.warn('[ERROR] Error returned from CV: %s' % e)
return
else:
return dom
def findComic(name, mode, issue, limityear=None, type=None):
#with mb_lock:
comicResults = None
comicLibrary = listLibrary()
comiclist = []
arcinfolist = []
commons = ['and', 'the', '&', '-']
for x in commons:
cnt = 0
for m in re.finditer(x, name.lower()):
cnt +=1
tehstart = m.start()
tehend = m.end()
if any([x == 'the', x == 'and']):
if len(name) == tehend:
tehend =-1
if not all([tehstart == 0, name[tehend] == ' ']) or not all([tehstart != 0, name[tehstart-1] == ' ', name[tehend] == ' ']):
continue
else:
name = name.replace(x, ' ', cnt)
originalname = name
if '+' in name:
name = re.sub('\+', 'PLUS', name)
pattern = re.compile(ur'\w+', re.UNICODE)
name = pattern.findall(name)
if '+' in originalname:
y = []
for x in name:
y.append(re.sub("PLUS", "%2B", x))
name = y
if limityear is None: limityear = 'None'
comicquery = name
if mylar.CONFIG.COMICVINE_API == 'None' or mylar.CONFIG.COMICVINE_API is None:
logger.warn('You have not specified your own ComicVine API key - this is a requirement. Get your own @ http://api.comicvine.com.')
return
else:
comicapi = mylar.CONFIG.COMICVINE_API
if type is None:
type = 'volume'
#let's find out how many results we get from the query...
searched = pullsearch(comicapi, comicquery, 0, type)
if searched is None:
return False
totalResults = searched.getElementsByTagName('number_of_total_results')[0].firstChild.wholeText
logger.fdebug("there are " + str(totalResults) + " search results...")
if not totalResults:
return False
if int(totalResults) > 1000:
logger.warn('Search returned more than 1000 hits [' + str(totalResults) + ']. Only displaying first 1000 results - use more specifics or the exact ComicID if required.')
totalResults = 1000
countResults = 0
while (countResults < int(totalResults)):
#logger.fdebug("querying " + str(countResults))
if countResults > 0:
offsetcount = countResults
searched = pullsearch(comicapi, comicquery, offsetcount, type)
comicResults = searched.getElementsByTagName(type)
body = ''
n = 0
if not comicResults:
break
for result in comicResults:
#retrieve the first xml tag (<tag>data</tag>)
#that the parser finds with name tagName:
arclist = []
if type == 'story_arc':
#call cv.py here to find out issue count in story arc
try:
logger.fdebug('story_arc ascension')
names = len(result.getElementsByTagName('name'))
n = 0
logger.fdebug('length: ' + str(names))
xmlpub = None #set this incase the publisher field isn't populated in the xml
while (n < names):
logger.fdebug(result.getElementsByTagName('name')[n].parentNode.nodeName)
if result.getElementsByTagName('name')[n].parentNode.nodeName == 'story_arc':
logger.fdebug('yes')
try:
xmlTag = result.getElementsByTagName('name')[n].firstChild.wholeText
xmlTag = xmlTag.rstrip()
logger.fdebug('name: ' + xmlTag)
except:
logger.error('There was a problem retrieving the given data from ComicVine. Ensure that www.comicvine.com is accessible.')
return
elif result.getElementsByTagName('name')[n].parentNode.nodeName == 'publisher':
logger.fdebug('publisher check.')
xmlpub = result.getElementsByTagName('name')[n].firstChild.wholeText
n+=1
except:
logger.warn('error retrieving story arc search results.')
return
siteurl = len(result.getElementsByTagName('site_detail_url'))
s = 0
logger.fdebug('length: ' + str(names))
xmlurl = None
while (s < siteurl):
logger.fdebug(result.getElementsByTagName('site_detail_url')[s].parentNode.nodeName)
if result.getElementsByTagName('site_detail_url')[s].parentNode.nodeName == 'story_arc':
try:
xmlurl = result.getElementsByTagName('site_detail_url')[s].firstChild.wholeText
except:
logger.error('There was a problem retrieving the given data from ComicVine. Ensure that www.comicvine.com is accessible.')
return
s+=1
xmlid = result.getElementsByTagName('id')[0].firstChild.wholeText
if xmlid is not None:
arcinfolist = storyarcinfo(xmlid)
logger.info('[IMAGE] : ' + arcinfolist['comicimage'])
comiclist.append({
'name': xmlTag,
'comicyear': arcinfolist['comicyear'],
'comicid': xmlid,
'cvarcid': xmlid,
'url': xmlurl,
'issues': arcinfolist['issues'],
'comicimage': arcinfolist['comicimage'],
'publisher': xmlpub,
'description': arcinfolist['description'],
'deck': arcinfolist['deck'],
'arclist': arcinfolist['arclist'],
'haveit': arcinfolist['haveit']
})
else:
comiclist.append({
'name': xmlTag,
'comicyear': arcyear,
'comicid': xmlid,
'url': xmlurl,
'issues': issuecount,
'comicimage': xmlimage,
'publisher': xmlpub,
'description': xmldesc,
'deck': xmldeck,
'arclist': arclist,
'haveit': haveit
})
logger.fdebug('IssueID\'s that are a part of ' + xmlTag + ' : ' + str(arclist))
else:
xmlcnt = result.getElementsByTagName('count_of_issues')[0].firstChild.wholeText
#here we can determine what called us, and either start gathering all issues or just limited ones.
if issue is not None and str(issue).isdigit():
#this gets buggered up with NEW/ONGOING series because the db hasn't been updated
#to reflect the proper count. Drop it by 1 to make sure.
limiter = int(issue) - 1
else: limiter = 0
#get the first issue # (for auto-magick calcs)
iss_len = len(result.getElementsByTagName('name'))
i=0
xmlfirst = '1'
xmllast = None
try:
while (i < iss_len):
if result.getElementsByTagName('name')[i].parentNode.nodeName == 'first_issue':
xmlfirst = result.getElementsByTagName('issue_number')[i].firstChild.wholeText
if '\xbd' in xmlfirst:
xmlfirst = '1' #if the first issue is 1/2, just assume 1 for logistics
elif result.getElementsByTagName('name')[i].parentNode.nodeName == 'last_issue':
xmllast = result.getElementsByTagName('issue_number')[i].firstChild.wholeText
if all([xmllast is not None, xmlfirst is not None]):
break
i+=1
except:
xmlfirst = '1'
if all([xmlfirst == xmllast, xmlfirst.isdigit(), xmlcnt == '0']):
xmlcnt = '1'
#logger.info('There are : ' + str(xmlcnt) + ' issues in this series.')
#logger.info('The first issue started at # ' + str(xmlfirst))
cnt_numerical = int(xmlcnt) + int(xmlfirst) # (of issues + start of first issue = numerical range)
#logger.info('The maximum issue number should be roughly # ' + str(cnt_numerical))
#logger.info('The limiter (issue max that we know of) is # ' + str(limiter))
if cnt_numerical >= limiter:
cnl = len (result.getElementsByTagName('name'))
cl = 0
xmlTag = 'None'
xmlimage = "cache/blankcover.jpg"
xml_lastissueid = 'None'
while (cl < cnl):
if result.getElementsByTagName('name')[cl].parentNode.nodeName == 'volume':
xmlTag = result.getElementsByTagName('name')[cl].firstChild.wholeText
#break
if result.getElementsByTagName('name')[cl].parentNode.nodeName == 'image':
xmlimage = result.getElementsByTagName('super_url')[0].firstChild.wholeText
if result.getElementsByTagName('name')[cl].parentNode.nodeName == 'last_issue':
xml_lastissueid = result.getElementsByTagName('id')[cl].firstChild.wholeText
cl+=1
if (result.getElementsByTagName('start_year')[0].firstChild) is not None:
xmlYr = result.getElementsByTagName('start_year')[0].firstChild.wholeText
else: xmlYr = "0000"
yearRange = []
tmpYr = re.sub('\?', '', xmlYr)
if tmpYr.isdigit():
yearRange.append(tmpYr)
tmpyearRange = int(xmlcnt) / 12
if float(tmpyearRange): tmpyearRange +1
possible_years = int(tmpYr) + tmpyearRange
for i in range(int(tmpYr), int(possible_years),1):
if not any(int(x) == int(i) for x in yearRange):
yearRange.append(str(i))
logger.fdebug('[RESULT][' + str(limityear) + '] ComicName:' + xmlTag + ' -- ' + str(xmlYr) + ' [Series years: ' + str(yearRange) + ']')
if tmpYr != xmlYr:
xmlYr = tmpYr
if any(map(lambda v: v in limityear, yearRange)) or limityear == 'None':
xmlurl = result.getElementsByTagName('site_detail_url')[0].firstChild.wholeText
idl = len (result.getElementsByTagName('id'))
idt = 0
xmlid = None
while (idt < idl):
if result.getElementsByTagName('id')[idt].parentNode.nodeName == 'volume':
xmlid = result.getElementsByTagName('id')[idt].firstChild.wholeText
break
idt+=1
if xmlid is None:
logger.error('Unable to figure out the comicid - skipping this : ' + str(xmlurl))
continue
publishers = result.getElementsByTagName('publisher')
if len(publishers) > 0:
pubnames = publishers[0].getElementsByTagName('name')
if len(pubnames) >0:
xmlpub = pubnames[0].firstChild.wholeText
else:
xmlpub = "Unknown"
else:
xmlpub = "Unknown"
#ignore specific publishers on a global scale here.
if mylar.CONFIG.BLACKLISTED_PUBLISHERS is not None and any([x for x in mylar.CONFIG.BLACKLISTED_PUBLISHERS if x.lower() == xmlpub.lower()]):
logger.fdebug('Blacklisted publisher [' + xmlpub + ']. Ignoring this result.')
continue
try:
xmldesc = result.getElementsByTagName('description')[0].firstChild.wholeText
except:
xmldesc = "None"
#this is needed to display brief synopsis for each series on search results page.
try:
xmldeck = result.getElementsByTagName('deck')[0].firstChild.wholeText
except:
xmldeck = "None"
xmltype = None
if xmldeck != 'None':
if any(['print' in xmldeck.lower(), 'digital' in xmldeck.lower(), 'paperback' in xmldeck.lower(), 'one shot' in re.sub('-', '', xmldeck.lower()).strip(), 'hardcover' in xmldeck.lower()]):
if all(['print' in xmldeck.lower(), 'reprint' not in xmldeck.lower()]):
xmltype = 'Print'
elif 'digital' in xmldeck.lower():
xmltype = 'Digital'
elif 'paperback' in xmldeck.lower():
xmltype = 'TPB'
elif 'hardcover' in xmldeck.lower():
xmltype = 'HC'
elif 'oneshot' in re.sub('-', '', xmldeck.lower()).strip():
xmltype = 'One-Shot'
else:
xmltype = 'Print'
if xmldesc != 'None' and xmltype is None:
if 'print' in xmldesc[:60].lower() and all(['print edition can be found' not in xmldesc.lower(), 'reprints' not in xmldesc.lower()]):
xmltype = 'Print'
elif 'digital' in xmldesc[:60].lower() and 'digital edition can be found' not in xmldesc.lower():
xmltype = 'Digital'
elif all(['paperback' in xmldesc[:60].lower(), 'paperback can be found' not in xmldesc.lower()]) or 'collects' in xmldesc[:60].lower():
xmltype = 'TPB'
elif 'hardcover' in xmldesc[:60].lower() and 'hardcover can be found' not in xmldesc.lower():
xmltype = 'HC'
elif any(['one-shot' in xmldesc[:60].lower(), 'one shot' in xmldesc[:60].lower()]) and any(['can be found' not in xmldesc.lower(), 'following the' not in xmldesc.lower()]):
i = 0
xmltype = 'One-Shot'
avoidwords = ['preceding', 'after the special', 'following the']
while i < 2:
if i == 0:
cbd = 'one-shot'
elif i == 1:
cbd = 'one shot'
tmp1 = xmldesc[:60].lower().find(cbd)
if tmp1 != -1:
for x in avoidwords:
tmp2 = xmldesc[:tmp1].lower().find(x)
if tmp2 != -1:
xmltype = 'Print'
i = 3
break
i+=1
else:
xmltype = 'Print'
if xmlid in comicLibrary:
haveit = comicLibrary[xmlid]
else:
haveit = "No"
comiclist.append({
'name': xmlTag,
'comicyear': xmlYr,
'comicid': xmlid,
'url': xmlurl,
'issues': xmlcnt,
'comicimage': xmlimage,
'publisher': xmlpub,
'description': xmldesc,
'deck': xmldeck,
'type': xmltype,
'haveit': haveit,
'lastissueid': xml_lastissueid,
'seriesrange': yearRange # returning additional information about series run polled from CV
})
#logger.fdebug('year: %s - constraint met: %s [%s] --- 4050-%s' % (xmlYr,xmlTag,xmlYr,xmlid))
else:
#logger.fdebug('year: ' + str(xmlYr) + ' - contraint not met. Has to be within ' + str(limityear))
pass
n+=1
#search results are limited to 100 and by pagination now...let's account for this.
countResults = countResults + 100
return comiclist
def storyarcinfo(xmlid):
comicLibrary = listStoryArcs()
arcinfo = {}
if mylar.CONFIG.COMICVINE_API == 'None' or mylar.CONFIG.COMICVINE_API is None:
logger.warn('You have not specified your own ComicVine API key - this is a requirement. Get your own @ http://api.comicvine.com.')
return
else:
comicapi = mylar.CONFIG.COMICVINE_API
#respawn to the exact id for the story arc and count the # of issues present.
ARCPULL_URL = mylar.CVURL + 'story_arc/4045-' + str(xmlid) + '/?api_key=' + str(comicapi) + '&field_list=issues,publisher,name,first_appeared_in_issue,deck,image&format=xml&offset=0'
#logger.fdebug('arcpull_url:' + str(ARCPULL_URL))
#new CV API restriction - one api request / second.
if mylar.CONFIG.CVAPI_RATE is None or mylar.CONFIG.CVAPI_RATE < 2:
time.sleep(2)
else:
time.sleep(mylar.CONFIG.CVAPI_RATE)
#download the file:
payload = None
try:
r = requests.get(ARCPULL_URL, params=payload, verify=mylar.CONFIG.CV_VERIFY, headers=mylar.CV_HEADERS)
except Exception as e:
logger.warn('While parsing data from ComicVine, got exception: %s' % e)
return
try:
arcdom = parseString(r.content)
except ExpatError:
if u'<title>Abnormal Traffic Detected' in r.content:
logger.error('ComicVine has banned this server\'s IP address because it exceeded the API rate limit.')
else:
logger.warn('While parsing data from ComicVine, got exception: %s for data: %s' % (e, r.content))
return
except Exception as e:
logger.warn('While parsing data from ComicVine, got exception: %s for data: %s' % (e, r.content))
return
try:
logger.fdebug('story_arc ascension')
issuedom = arcdom.getElementsByTagName('issue')
issuecount = len( issuedom ) #arcdom.getElementsByTagName('issue') )
isc = 0
arclist = ''
ordernum = 1
for isd in issuedom:
zeline = isd.getElementsByTagName('id')
isdlen = len( zeline )
isb = 0
while ( isb < isdlen):
if isc == 0:
arclist = str(zeline[isb].firstChild.wholeText).strip() + ',' + str(ordernum)
else:
arclist += '|' + str(zeline[isb].firstChild.wholeText).strip() + ',' + str(ordernum)
ordernum+=1
isb+=1
isc+=1
except:
logger.fdebug('unable to retrive issue count - nullifying value.')
issuecount = 0
try:
firstid = None
arcyear = None
fid = len ( arcdom.getElementsByTagName('id') )
fi = 0
while (fi < fid):
if arcdom.getElementsByTagName('id')[fi].parentNode.nodeName == 'first_appeared_in_issue':
if not arcdom.getElementsByTagName('id')[fi].firstChild.wholeText == xmlid:
logger.fdebug('hit it.')
firstid = arcdom.getElementsByTagName('id')[fi].firstChild.wholeText
break # - dont' break out here as we want to gather ALL the issue ID's since it's here
fi+=1
logger.fdebug('firstid: ' + str(firstid))
if firstid is not None:
firstdom = cv.pulldetails(comicid=None, type='firstissue', issueid=firstid)
logger.fdebug('success')
arcyear = cv.Getissue(firstid,firstdom,'firstissue')
except:
logger.fdebug('Unable to retrieve first issue details. Not caclulating at this time.')
try:
xmlimage = arcdom.getElementsByTagName('super_url')[0].firstChild.wholeText
except:
xmlimage = "cache/blankcover.jpg"
try:
xmldesc = arcdom.getElementsByTagName('desc')[0].firstChild.wholeText
except:
xmldesc = "None"
try:
xmlpub = arcdom.getElementsByTagName('publisher')[0].firstChild.wholeText
except:
xmlpub = "None"
try:
xmldeck = arcdom.getElementsByTagName('deck')[0].firstChild.wholeText
except:
xmldeck = "None"
if xmlid in comicLibrary:
haveit = comicLibrary[xmlid]
else:
haveit = "No"
arcinfo = {
#'name': xmlTag, #theese four are passed into it only when it's a new add
#'url': xmlurl, #needs to be modified for refreshing to work completely.
#'publisher': xmlpub,
'comicyear': arcyear,
'comicid': xmlid,
'issues': issuecount,
'comicimage': xmlimage,
'description': xmldesc,
'deck': xmldeck,
'arclist': arclist,
'haveit': haveit,
'publisher': xmlpub
}
return arcinfo
| 27,511 | Python | .py | 492 | 36.660569 | 343 | 0.485989 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,235 | librarysync.py | evilhero_mylar/mylar/librarysync.py | # -*- coding: utf-8 -*-
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import os
import glob
import re
import shutil
import random
import mylar
from mylar import db, logger, helpers, importer, updater, filechecker
# You can scan a single directory and append it to the current library by specifying append=True
def libraryScan(dir=None, append=False, ComicID=None, ComicName=None, cron=None, queue=None):
if cron and not mylar.LIBRARYSCAN:
return
if not dir:
dir = mylar.CONFIG.COMIC_DIR
# If we're appending a dir, it's coming from the post processor which is
# already bytestring
if not append:
dir = dir.encode(mylar.SYS_ENCODING)
if not os.path.isdir(dir):
logger.warn('Cannot find directory: %s. Not scanning' % dir.decode(mylar.SYS_ENCODING, 'replace'))
return "Fail"
logger.info('Scanning comic directory: %s' % dir.decode(mylar.SYS_ENCODING, 'replace'))
basedir = dir
comic_list = []
failure_list = []
utter_failure_list = []
comiccnt = 0
extensions = ('cbr','cbz')
cv_location = []
cbz_retry = 0
mylar.IMPORT_STATUS = 'Now attempting to parse files for additional information'
myDB = db.DBConnection()
#mylar.IMPORT_PARSED_COUNT #used to count what #/totalfiles the filename parser is currently on
for r, d, f in os.walk(dir):
for files in f:
mylar.IMPORT_FILES +=1
if any(files.lower().endswith('.' + x.lower()) for x in extensions):
comicpath = os.path.join(r, files)
if mylar.CONFIG.IMP_PATHS is True:
if myDB.select('SELECT * FROM comics JOIN issues WHERE issues.Status="Downloaded" AND ComicLocation=? AND issues.Location=?', [r.decode(mylar.SYS_ENCODING, 'replace'), files.decode(mylar.SYS_ENCODING, 'replace')]):
logger.info('Skipped known issue path: %s' % comicpath)
continue
comic = files
comicsize = os.path.getsize(comicpath)
logger.fdebug('Comic: ' + comic + ' [' + comicpath + '] - ' + str(comicsize) + ' bytes')
try:
t = filechecker.FileChecker(dir=r, file=comic)
results = t.listFiles()
#logger.info(results)
#'type': re.sub('\.','', filetype).strip(),
#'sub': path_list,
#'volume': volume,
#'match_type': match_type,
#'comicfilename': filename,
#'comiclocation': clocation,
#'series_name': series_name,
#'series_volume': issue_volume,
#'series_year': issue_year,
#'justthedigits': issue_number,
#'annualcomicid': annual_comicid,
#'scangroup': scangroup}
if results:
resultline = '[PARSE-' + results['parse_status'].upper() + ']'
resultline += '[SERIES: ' + results['series_name'] + ']'
if results['series_volume'] is not None:
resultline += '[VOLUME: ' + results['series_volume'] + ']'
if results['issue_year'] is not None:
resultline += '[ISSUE YEAR: ' + str(results['issue_year']) + ']'
if results['issue_number'] is not None:
resultline += '[ISSUE #: ' + results['issue_number'] + ']'
logger.fdebug(resultline)
else:
logger.fdebug('[PARSED] FAILURE.')
continue
# We need the unicode path to use for logging, inserting into database
unicode_comic_path = comicpath.decode(mylar.SYS_ENCODING, 'replace')
if results['parse_status'] == 'success':
comic_list.append({'ComicFilename': comic,
'ComicLocation': comicpath,
'ComicSize': comicsize,
'Unicode_ComicLocation': unicode_comic_path,
'parsedinfo': {'series_name': results['series_name'],
'series_volume': results['series_volume'],
'issue_year': results['issue_year'],
'issue_number': results['issue_number']}
})
comiccnt +=1
mylar.IMPORT_PARSED_COUNT +=1
else:
failure_list.append({'ComicFilename': comic,
'ComicLocation': comicpath,
'ComicSize': comicsize,
'Unicode_ComicLocation': unicode_comic_path,
'parsedinfo': {'series_name': results['series_name'],
'series_volume': results['series_volume'],
'issue_year': results['issue_year'],
'issue_number': results['issue_number']}
})
mylar.IMPORT_FAILURE_COUNT +=1
if comic.endswith('.cbz'):
cbz_retry +=1
except Exception, e:
logger.info('bang')
utter_failure_list.append({'ComicFilename': comic,
'ComicLocation': comicpath,
'ComicSize': comicsize,
'Unicode_ComicLocation': unicode_comic_path,
'parsedinfo': None,
'error': e
})
logger.info('[' + str(e) + '] FAILURE encountered. Logging the error for ' + comic + ' and continuing...')
mylar.IMPORT_FAILURE_COUNT +=1
if comic.endswith('.cbz'):
cbz_retry +=1
continue
if 'cvinfo' in files:
cv_location.append(r)
logger.fdebug('CVINFO found: ' + os.path.join(r))
mylar.IMPORT_TOTALFILES = comiccnt
logger.info('I have successfully discovered & parsed a total of ' + str(comiccnt) + ' files....analyzing now')
logger.info('I have not been able to determine what ' + str(len(failure_list)) + ' files are')
logger.info('However, ' + str(cbz_retry) + ' out of the ' + str(len(failure_list)) + ' files are in a cbz format, which may contain metadata.')
logger.info('[ERRORS] I have encountered ' + str(len(utter_failure_list)) + ' file-scanning errors during the scan, but have recorded the necessary information.')
mylar.IMPORT_STATUS = 'Successfully parsed ' + str(comiccnt) + ' files'
#return queue.put(valreturn)
if len(utter_failure_list) > 0:
logger.fdebug('Failure list: %s' % utter_failure_list)
#let's load in the watchlist to see if we have any matches.
logger.info("loading in the watchlist to see if a series is being watched already...")
watchlist = myDB.select("SELECT * from comics")
ComicName = []
DisplayName = []
ComicYear = []
ComicPublisher = []
ComicTotal = []
ComicID = []
ComicLocation = []
AltName = []
watchcnt = 0
watch_kchoice = []
watchchoice = {}
import_by_comicids = []
import_comicids = {}
for watch in watchlist:
#use the comicname_filesafe to start
watchdisplaycomic = watch['ComicName'].encode('utf-8').strip() #re.sub('[\_\#\,\/\:\;\!\$\%\&\+\'\?\@]', ' ', watch['ComicName']).encode('utf-8').strip()
# let's clean up the name, just in case for comparison purposes...
watchcomic = re.sub('[\_\#\,\/\:\;\.\-\!\$\%\&\+\'\?\@]', '', watch['ComicName_Filesafe']).encode('utf-8').strip()
#watchcomic = re.sub('\s+', ' ', str(watchcomic)).strip()
if ' the ' in watchcomic.lower():
#drop the 'the' from the watchcomic title for proper comparisons.
watchcomic = watchcomic[-4:]
alt_chk = "no" # alt-checker flag (default to no)
# account for alternate names as well
if watch['AlternateSearch'] is not None and watch['AlternateSearch'] is not 'None':
altcomic = re.sub('[\_\#\,\/\:\;\.\-\!\$\%\&\+\'\?\@]', '', watch['AlternateSearch']).encode('utf-8').strip()
#altcomic = re.sub('\s+', ' ', str(altcomic)).strip()
AltName.append(altcomic)
alt_chk = "yes" # alt-checker flag
ComicName.append(watchcomic)
DisplayName.append(watchdisplaycomic)
ComicYear.append(watch['ComicYear'])
ComicPublisher.append(watch['ComicPublisher'])
ComicTotal.append(watch['Total'])
ComicID.append(watch['ComicID'])
ComicLocation.append(watch['ComicLocation'])
watchcnt+=1
logger.info("Successfully loaded " + str(watchcnt) + " series from your watchlist.")
ripperlist=['digital-',
'empire',
'dcp']
watchfound = 0
datelist = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
# datemonth = {'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10,'eleven':$
# #search for number as text, and change to numeric
# for numbs in basnumbs:
# #logger.fdebug("numbs:" + str(numbs))
# if numbs in ComicName.lower():
# numconv = basnumbs[numbs]
# #logger.fdebug("numconv: " + str(numconv))
issueid_list = []
cvscanned_loc = None
cvinfo_CID = None
cnt = 0
mylar.IMPORT_STATUS = '[0%] Now parsing individual filenames for metadata if available'
for i in comic_list:
mylar.IMPORT_STATUS = '[' + str(cnt) + '/' + str(comiccnt) + '] Now parsing individual filenames for metadata if available'
logger.fdebug('Analyzing : ' + i['ComicFilename'])
comfilename = i['ComicFilename']
comlocation = i['ComicLocation']
issueinfo = None
#probably need to zero these issue-related metadata to None so we can pick the best option
issuevolume = None
#Make sure cvinfo is checked for FIRST (so that CID can be attached to all files properly thereafter as they're scanned in)
if os.path.dirname(comlocation) in cv_location and os.path.dirname(comlocation) != cvscanned_loc:
#if comfilename == 'cvinfo':
logger.info('comfilename: ' + comfilename)
logger.info('cvscanned_loc: ' + str(cv_location))
logger.info('comlocation: ' + os.path.dirname(comlocation))
#if cvscanned_loc != comlocation:
try:
with open(os.path.join(os.path.dirname(comlocation), 'cvinfo')) as f:
urllink = f.readline()
if urllink:
cid = urllink.strip()
pattern = re.compile(r"^.*?\b(49|4050)-(?P<num>\d{2,})\b.*$", re.I)
match = pattern.match(cid)
if match:
cvinfo_CID = match.group("num")
logger.info('CVINFO file located within directory. Attaching everything in directory that is valid to ComicID: ' + str(cvinfo_CID))
#store the location of the cvinfo so it's applied to the correct directory (since we're scanning multile direcorties usually)
cvscanned_loc = os.path.dirname(comlocation)
else:
logger.error("Could not read cvinfo file properly (or it does not contain any data)")
except (OSError, IOError):
logger.error("Could not read cvinfo file properly (or it does not contain any data)")
#else:
# don't scan in it again if it's already been done initially
# continue
if mylar.CONFIG.IMP_METADATA:
#if read tags is enabled during import, check here.
if i['ComicLocation'].endswith('.cbz'):
logger.fdebug('[IMPORT-CBZ] Metatagging checking enabled.')
logger.info('[IMPORT-CBZ} Attempting to read tags present in filename: ' + i['ComicLocation'])
try:
issueinfo = helpers.IssueDetails(i['ComicLocation'], justinfo=True)
except:
logger.fdebug('[IMPORT-CBZ] Unable to retrieve metadata - possibly doesn\'t exist. Ignoring meta-retrieval')
pass
else:
logger.info('issueinfo: ' + str(issueinfo))
if issueinfo is None:
logger.fdebug('[IMPORT-CBZ] No valid metadata contained within filename. Dropping down to parsing the filename itself.')
pass
else:
issuenotes_id = None
logger.info('[IMPORT-CBZ] Successfully retrieved some tags. Lets see what I can figure out.')
comicname = issueinfo[0]['series']
if comicname is not None:
logger.fdebug('[IMPORT-CBZ] Series Name: ' + comicname)
as_d = filechecker.FileChecker()
as_dyninfo = as_d.dynamic_replace(comicname)
logger.fdebug('Dynamic-ComicName: ' + as_dyninfo['mod_seriesname'])
else:
logger.fdebug('[IMPORT-CBZ] No series name found within metadata. This is bunk - dropping down to file parsing for usable information.')
issueinfo = None
issue_number = None
if issueinfo is not None:
try:
issueyear = issueinfo[0]['year']
except:
issueyear = None
#if the issue number is a non-numeric unicode string, this will screw up along with impID
issue_number = issueinfo[0]['issue_number']
if issue_number is not None:
logger.fdebug('[IMPORT-CBZ] Issue Number: ' + issue_number)
else:
issue_number = i['parsed']['issue_number']
if 'annual' in comicname.lower() or 'annual' in comfilename.lower():
if issue_number is None or issue_number == 'None':
logger.info('Annual detected with no issue number present within metadata. Assuming year as issue.')
try:
issue_number = 'Annual ' + str(issueyear)
except:
issue_number = 'Annual ' + i['parsed']['issue_year']
else:
logger.info('Annual detected with issue number present within metadata.')
if 'annual' not in issue_number.lower():
issue_number = 'Annual ' + issue_number
mod_series = re.sub('annual', '', comicname, flags=re.I).strip()
else:
mod_series = comicname
logger.fdebug('issue number SHOULD Be: ' + issue_number)
try:
issuetitle = issueinfo[0]['title']
except:
issuetitle = None
try:
issueyear = issueinfo[0]['year']
except:
issueyear = None
try:
issuevolume = str(issueinfo[0]['volume'])
if all([issuevolume is not None, issuevolume != 'None', not issuevolume.lower().startswith('v')]):
issuevolume = 'v' + str(issuevolume)
if any([issuevolume is None, issuevolume == 'None']):
logger.info('EXCEPT] issue volume is NONE')
issuevolume = None
else:
logger.fdebug('[TRY]issue volume is: ' + str(issuevolume))
except:
logger.fdebug('[EXCEPT]issue volume is: ' + str(issuevolume))
issuevolume = None
if any([comicname is None, comicname == 'None', issue_number is None, issue_number == 'None']):
logger.fdebug('[IMPORT-CBZ] Improperly tagged file as the metatagging is invalid. Ignoring meta and just parsing the filename.')
issueinfo = None
pass
else:
# if used by ComicTagger, Notes field will have the IssueID.
issuenotes = issueinfo[0]['notes']
logger.fdebug('[IMPORT-CBZ] Notes: ' + issuenotes)
if issuenotes is not None and issuenotes != 'None':
if 'Issue ID' in issuenotes:
st_find = issuenotes.find('Issue ID')
tmp_issuenotes_id = re.sub("[^0-9]", " ", issuenotes[st_find:]).strip()
if tmp_issuenotes_id.isdigit():
issuenotes_id = tmp_issuenotes_id
logger.fdebug('[IMPORT-CBZ] Successfully retrieved CV IssueID for ' + comicname + ' #' + issue_number + ' [' + str(issuenotes_id) + ']')
elif 'CVDB' in issuenotes:
st_find = issuenotes.find('CVDB')
tmp_issuenotes_id = re.sub("[^0-9]", " ", issuenotes[st_find:]).strip()
if tmp_issuenotes_id.isdigit():
issuenotes_id = tmp_issuenotes_id
logger.fdebug('[IMPORT-CBZ] Successfully retrieved CV IssueID for ' + comicname + ' #' + issue_number + ' [' + str(issuenotes_id) + ']')
else:
logger.fdebug('[IMPORT-CBZ] Unable to retrieve IssueID from meta-tagging. If there is other metadata present I will use that.')
logger.fdebug('[IMPORT-CBZ] Adding ' + comicname + ' to the import-queue!')
#impid = comicname + '-' + str(issueyear) + '-' + str(issue_number) #com_NAME + "-" + str(result_comyear) + "-" + str(comiss)
impid = str(random.randint(1000000,99999999))
logger.fdebug('[IMPORT-CBZ] impid: ' + str(impid))
#make sure we only add in those issueid's which don't already have a comicid attached via the cvinfo scan above (this is for reverse-lookup of issueids)
issuepopulated = False
if cvinfo_CID is None:
if issuenotes_id is None:
logger.info('[IMPORT-CBZ] No ComicID detected where it should be. Bypassing this metadata entry and going the parsing route [' + comfilename + ']')
else:
#we need to store the impid here as well so we can look it up.
issueid_list.append({'issueid': issuenotes_id,
'importinfo': {'impid': impid,
'comicid': None,
'comicname': comicname,
'dynamicname': as_dyninfo['mod_seriesname'],
'comicyear': issueyear,
'issuenumber': issue_number,
'volume': issuevolume,
'comfilename': comfilename,
'comlocation': comlocation.decode(mylar.SYS_ENCODING)}
})
mylar.IMPORT_CID_COUNT +=1
issuepopulated = True
if issuepopulated == False:
if cvscanned_loc == os.path.dirname(comlocation):
cv_cid = cvinfo_CID
logger.fdebug('[IMPORT-CBZ] CVINFO_COMICID attached : ' + str(cv_cid))
else:
cv_cid = None
import_by_comicids.append({
"impid": impid,
"comicid": cv_cid,
"watchmatch": None,
"displayname": mod_series,
"comicname": comicname,
"dynamicname": as_dyninfo['mod_seriesname'],
"comicyear": issueyear,
"issuenumber": issue_number,
"volume": issuevolume,
"issueid": issuenotes_id,
"comfilename": comfilename,
"comlocation": comlocation.decode(mylar.SYS_ENCODING)
})
mylar.IMPORT_CID_COUNT +=1
else:
pass
#logger.fdebug(i['ComicFilename'] + ' is not in a metatagged format (cbz). Bypassing reading of the metatags')
if issueinfo is None:
if i['parsedinfo']['issue_number'] is None:
if 'annual' in i['parsedinfo']['series_name'].lower():
logger.fdebug('Annual detected with no issue number present. Assuming year as issue.')##1 issue')
if i['parsedinfo']['issue_year'] is not None:
issuenumber = 'Annual ' + str(i['parsedinfo']['issue_year'])
else:
issuenumber = 'Annual 1'
else:
issuenumber = i['parsedinfo']['issue_number']
if 'annual' in i['parsedinfo']['series_name'].lower():
mod_series = re.sub('annual', '', i['parsedinfo']['series_name'], flags=re.I).strip()
logger.fdebug('Annual detected with no issue number present. Assuming year as issue.')##1 issue')
if i['parsedinfo']['issue_number'] is not None:
issuenumber = 'Annual ' + str(i['parsedinfo']['issue_number'])
else:
if i['parsedinfo']['issue_year'] is not None:
issuenumber = 'Annual ' + str(i['parsedinfo']['issue_year'])
else:
issuenumber = 'Annual 1'
else:
mod_series = i['parsedinfo']['series_name']
issuenumber = i['parsedinfo']['issue_number']
logger.fdebug('[' + mod_series + '] Adding to the import-queue!')
isd = filechecker.FileChecker()
is_dyninfo = isd.dynamic_replace(helpers.conversion(mod_series))
logger.fdebug('Dynamic-ComicName: ' + is_dyninfo['mod_seriesname'])
#impid = dispname + '-' + str(result_comyear) + '-' + str(comiss) #com_NAME + "-" + str(result_comyear) + "-" + str(comiss)
impid = str(random.randint(1000000,99999999))
logger.fdebug("impid: " + str(impid))
if cvscanned_loc == os.path.dirname(comlocation):
cv_cid = cvinfo_CID
logger.fdebug('CVINFO_COMICID attached : ' + str(cv_cid))
else:
cv_cid = None
if issuevolume is None:
logger.fdebug('issue volume is : ' + str(issuevolume))
if i['parsedinfo']['series_volume'] is None:
issuevolume = None
else:
if str(i['parsedinfo']['series_volume'].lower()).startswith('v'):
issuevolume = i['parsedinfo']['series_volume']
else:
issuevolume = 'v' + str(i['parsedinfo']['series_volume'])
else:
logger.fdebug('issue volume not none : ' + str(issuevolume))
if issuevolume.lower().startswith('v'):
issuevolume = issuevolume
else:
issuevolume = 'v' + str(issuevolume)
logger.fdebug('IssueVolume is : ' + str(issuevolume))
import_by_comicids.append({
"impid": impid,
"comicid": cv_cid,
"issueid": None,
"watchmatch": None, #watchmatch (should be true/false if it already exists on watchlist)
"displayname": mod_series,
"comicname": i['parsedinfo']['series_name'],
"dynamicname": is_dyninfo['mod_seriesname'].lower(),
"comicyear": i['parsedinfo']['issue_year'],
"issuenumber": issuenumber, #issuenumber,
"volume": issuevolume,
"comfilename": comfilename,
"comlocation": helpers.conversion(comlocation)
})
cnt+=1
#logger.fdebug('import_by_ids: ' + str(import_by_comicids))
#reverse lookup all of the gathered IssueID's in order to get the related ComicID
reverse_issueids = []
for x in issueid_list:
reverse_issueids.append(x['issueid'])
vals = []
if len(reverse_issueids) > 0:
mylar.IMPORT_STATUS = 'Now Reverse looking up ' + str(len(reverse_issueids)) + ' IssueIDs to get the ComicIDs'
vals = mylar.cv.getComic(None, 'import', comicidlist=reverse_issueids)
#logger.fdebug('vals returned:' + str(vals))
if len(watch_kchoice) > 0:
watchchoice['watchlist'] = watch_kchoice
#logger.fdebug("watchchoice: " + str(watchchoice))
logger.info("I have found " + str(watchfound) + " out of " + str(comiccnt) + " comics for series that are being watched.")
wat = 0
comicids = []
if watchfound > 0:
if mylar.CONFIG.IMP_MOVE:
logger.info('You checked off Move Files...so that\'s what I am going to do')
#check to see if Move Files is enabled.
#if not being moved, set the archive bit.
logger.fdebug('Moving files into appropriate directory')
while (wat < watchfound):
watch_the_list = watchchoice['watchlist'][wat]
watch_comlocation = watch_the_list['ComicLocation']
watch_comicid = watch_the_list['ComicID']
watch_comicname = watch_the_list['ComicName']
watch_comicyear = watch_the_list['ComicYear']
watch_comiciss = watch_the_list['ComicIssue']
logger.fdebug('ComicLocation: ' + watch_comlocation)
orig_comlocation = watch_the_list['OriginalLocation']
orig_filename = watch_the_list['OriginalFilename']
logger.fdebug('Orig. Location: ' + orig_comlocation)
logger.fdebug('Orig. Filename: ' + orig_filename)
#before moving check to see if Rename to Mylar structure is enabled.
if mylar.CONFIG.IMP_RENAME:
logger.fdebug('Renaming files according to configuration details : ' + str(mylar.CONFIG.FILE_FORMAT))
renameit = helpers.rename_param(watch_comicid, watch_comicname, watch_comicyear, watch_comiciss)
nfilename = renameit['nfilename']
dst_path = os.path.join(watch_comlocation, nfilename)
if str(watch_comicid) not in comicids:
comicids.append(watch_comicid)
else:
logger.fdebug('Renaming files not enabled, keeping original filename(s)')
dst_path = os.path.join(watch_comlocation, orig_filename)
#os.rename(os.path.join(self.nzb_folder, str(ofilename)), os.path.join(self.nzb_folder,str(nfilename + ext)))
#src = os.path.join(, str(nfilename + ext))
logger.fdebug('I am going to move ' + orig_comlocation + ' to ' + dst_path)
try:
shutil.move(orig_comlocation, dst_path)
except (OSError, IOError):
logger.info("Failed to move directory - check directories and manually re-run.")
wat+=1
else:
# if move files isn't enabled, let's set all found comics to Archive status :)
while (wat < watchfound):
watch_the_list = watchchoice['watchlist'][wat]
watch_comicid = watch_the_list['ComicID']
watch_issue = watch_the_list['ComicIssue']
logger.fdebug('ComicID: ' + str(watch_comicid))
logger.fdebug('Issue#: ' + str(watch_issue))
issuechk = myDB.selectone("SELECT * from issues where ComicID=? AND INT_IssueNumber=?", [watch_comicid, watch_issue]).fetchone()
if issuechk is None:
logger.fdebug('No matching issues for this comic#')
else:
logger.fdebug('...Existing status: ' + str(issuechk['Status']))
control = {"IssueID": issuechk['IssueID']}
values = {"Status": "Archived"}
logger.fdebug('...changing status of ' + str(issuechk['Issue_Number']) + ' to Archived ')
myDB.upsert("issues", values, control)
if str(watch_comicid) not in comicids:
comicids.append(watch_comicid)
wat+=1
if comicids is None: pass
else:
c_upd = len(comicids)
c = 0
while (c < c_upd ):
logger.fdebug('Rescanning.. ' + str(c))
updater.forceRescan(c)
if not len(import_by_comicids):
return "Completed"
if len(import_by_comicids) > 0 or len(vals) > 0:
#import_comicids['comic_info'] = import_by_comicids
#if vals:
# import_comicids['issueid_info'] = vals
#else:
# import_comicids['issueid_info'] = None
if vals:
cvimport_comicids = vals
import_cv_ids = len(vals)
else:
cvimport_comicids = None
import_cv_ids = 0
else:
import_cv_ids = 0
cvimport_comicids = None
return {'import_by_comicids': import_by_comicids,
'import_count': len(import_by_comicids),
'CV_import_comicids': cvimport_comicids,
'import_cv_ids': import_cv_ids,
'issueid_list': issueid_list,
'failure_list': failure_list,
'utter_failure_list': utter_failure_list}
def scanLibrary(scan=None, queue=None):
mylar.IMPORT_FILES = 0
mylar.IMPORT_PARSED_COUNT = 0
valreturn = []
if scan:
try:
soma = libraryScan(queue=queue)
except Exception, e:
logger.error('[IMPORT] Unable to complete the scan: %s' % e)
mylar.IMPORT_STATUS = None
valreturn.append({"somevalue": 'self.ie',
"result": 'error'})
return queue.put(valreturn)
if soma == "Completed":
logger.info('[IMPORT] Sucessfully completed import.')
elif soma == "Fail":
mylar.IMPORT_STATUS = 'Failure'
valreturn.append({"somevalue": 'self.ie',
"result": 'error'})
return queue.put(valreturn)
else:
mylar.IMPORT_STATUS = 'Now adding the completed results to the DB.'
logger.info('[IMPORT] Parsing/Reading of files completed!')
logger.info('[IMPORT] Attempting to import ' + str(int(soma['import_cv_ids'] + soma['import_count'])) + ' files into your watchlist.')
logger.info('[IMPORT-BREAKDOWN] Files with ComicIDs successfully extracted: ' + str(soma['import_cv_ids']))
logger.info('[IMPORT-BREAKDOWN] Files that had to be parsed: ' + str(soma['import_count']))
logger.info('[IMPORT-BREAKDOWN] Files that were unable to be parsed: ' + str(len(soma['failure_list'])))
logger.info('[IMPORT-BREAKDOWN] Files that caused errors during the import: ' + str(len(soma['utter_failure_list'])))
#logger.info('[IMPORT-BREAKDOWN] Failure Files: ' + str(soma['failure_list']))
myDB = db.DBConnection()
#first we do the CV ones.
if int(soma['import_cv_ids']) > 0:
for i in soma['CV_import_comicids']:
#we need to find the impid in the issueid_list as that holds the impid + other info
abc = [x for x in soma['issueid_list'] if x['issueid'] == i['IssueID']]
ghi = abc[0]['importinfo']
nspace_dynamicname = re.sub('[\|\s]', '', ghi['dynamicname'].lower()).strip()
#these all have related ComicID/IssueID's...just add them as is.
controlValue = {"impID": ghi['impid']}
newValue = {"Status": "Not Imported",
"ComicName": helpers.conversion(i['ComicName']),
"DisplayName": helpers.conversion(i['ComicName']),
"DynamicName": helpers.conversion(nspace_dynamicname),
"ComicID": i['ComicID'],
"IssueID": i['IssueID'],
"IssueNumber": helpers.conversion(i['Issue_Number']),
"Volume": ghi['volume'],
"ComicYear": ghi['comicyear'],
"ComicFilename": helpers.conversion(ghi['comfilename']),
"ComicLocation": helpers.conversion(ghi['comlocation']),
"ImportDate": helpers.today(),
"WatchMatch": None} #i['watchmatch']}
myDB.upsert("importresults", newValue, controlValue)
if int(soma['import_count']) > 0:
for ss in soma['import_by_comicids']:
nspace_dynamicname = re.sub('[\|\s]', '', ss['dynamicname'].lower()).strip()
controlValue = {"impID": ss['impid']}
newValue = {"ComicYear": ss['comicyear'],
"Status": "Not Imported",
"ComicName": helpers.conversion(ss['comicname']),
"DisplayName": helpers.conversion(ss['displayname']),
"DynamicName": helpers.conversion(nspace_dynamicname),
"ComicID": ss['comicid'], #if it's been scanned in for cvinfo, this will be the CID - otherwise it's None
"IssueID": None,
"Volume": ss['volume'],
"IssueNumber": helpers.conversion(ss['issuenumber']),
"ComicFilename": helpers.conversion(ss['comfilename']),
"ComicLocation": helpers.conversion(ss['comlocation']),
"ImportDate": helpers.today(),
"WatchMatch": ss['watchmatch']}
myDB.upsert("importresults", newValue, controlValue)
# because we could be adding volumes/series that span years, we need to account for this
# add the year to the db under the term, valid-years
# add the issue to the db under the term, min-issue
#locate metadata here.
# unzip -z filename.cbz will show the comment field of the zip which contains the metadata.
#self.importResults()
mylar.IMPORT_STATUS = 'Import completed.'
valreturn.append({"somevalue": 'self.ie',
"result": 'success'})
return queue.put(valreturn)
| 39,597 | Python | .py | 630 | 41.515873 | 234 | 0.486008 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,236 | moveit.py | evilhero_mylar/mylar/moveit.py | import mylar
from mylar import db, logger, helpers, updater, filechecker
import os
import shutil
import ast
def movefiles(comicid, comlocation, imported):
#comlocation is destination
#comicid is used for rename
files_moved = []
try:
imported = ast.literal_eval(imported)
except ValueError:
pass
myDB = db.DBConnection()
logger.fdebug('comlocation is : ' + comlocation)
logger.fdebug('original comicname is : ' + imported['ComicName'])
impres = imported['filelisting']
if impres is not None:
if all([mylar.CONFIG.CREATE_FOLDERS is False, not os.path.isdir(comlocation)]):
checkdirectory = filechecker.validateAndCreateDirectory(comlocation, True)
if not checkdirectory:
logger.warn('Error trying to validate/create directory. Aborting this process at this time.')
return
for impr in impres:
srcimp = impr['comiclocation']
orig_filename = impr['comicfilename']
#before moving check to see if Rename to Mylar structure is enabled.
if mylar.CONFIG.IMP_RENAME and mylar.CONFIG.FILE_FORMAT != '':
logger.fdebug("Renaming files according to configuration details : " + str(mylar.CONFIG.FILE_FORMAT))
renameit = helpers.rename_param(comicid, imported['ComicName'], impr['issuenumber'], orig_filename)
nfilename = renameit['nfilename']
dstimp = os.path.join(comlocation, nfilename)
else:
logger.fdebug("Renaming files not enabled, keeping original filename(s)")
dstimp = os.path.join(comlocation, orig_filename)
logger.info("moving " + srcimp + " ... to " + dstimp)
try:
shutil.move(srcimp, dstimp)
files_moved.append({'srid': imported['srid'],
'filename': impr['comicfilename'],
'import_id': impr['import_id']})
except (OSError, IOError):
logger.error("Failed to move files - check directories and manually re-run.")
logger.fdebug("all files moved.")
#now that it's moved / renamed ... we remove it from importResults or mark as completed.
if len(files_moved) > 0:
logger.info('files_moved: ' + str(files_moved))
for result in files_moved:
try:
res = result['import_id']
except:
#if it's an 'older' import that wasn't imported, just make it a basic match so things can move and update properly.
controlValue = {"ComicFilename": result['filename'],
"SRID": result['srid']}
newValue = {"Status": "Imported",
"ComicID": comicid}
else:
controlValue = {"impID": result['import_id'],
"ComicFilename": result['filename']}
newValue = {"Status": "Imported",
"SRID": result['srid'],
"ComicID": comicid}
myDB.upsert("importresults", newValue, controlValue)
return
def archivefiles(comicid, comlocation, imported):
myDB = db.DBConnection()
# if move files isn't enabled, let's set all found comics to Archive status :)
try:
imported = ast.literal_eval(imported)
except Exception as e:
logger.warn('[%s] Error encountered converting import data' % e)
ComicName = imported['ComicName']
impres = imported['filelisting']
if impres is not None:
scandir = []
for impr in impres:
srcimp = impr['comiclocation']
orig_filename = impr['comicfilename']
if not any([os.path.abspath(os.path.join(srcimp, os.pardir)) == x for x in scandir]):
scandir.append(os.path.abspath(os.path.join(srcimp, os.pardir)))
for sdir in scandir:
logger.info('Updating issue information and setting status to Archived for location: ' + sdir)
updater.forceRescan(comicid, archive=sdir) #send to rescanner with archive mode turned on
logger.info('Now scanning in files.')
updater.forceRescan(comicid)
for result in impres:
try:
res = result['import_id']
except:
#if it's an 'older' import that wasn't imported, just make it a basic match so things can move and update properly.
controlValue = {"ComicFilename": result['comicfilename'],
"SRID": imported['srid']}
newValue = {"Status": "Imported",
"ComicID": comicid}
else:
controlValue = {"impID": result['import_id'],
"ComicFilename": result['comicfilename']}
newValue = {"Status": "Imported",
"SRID": imported['srid'],
"ComicID": comicid}
myDB.upsert("importresults", newValue, controlValue)
return
| 5,320 | Python | .py | 102 | 38.686275 | 131 | 0.560108 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,237 | searchit.py | evilhero_mylar/mylar/searchit.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import mylar
from mylar import logger, helpers
class CurrentSearcher():
def __init__(self, **kwargs):
pass
def run(self):
logger.info('[SEARCH] Running Search for Wanted.')
helpers.job_management(write=True, job='Auto-Search', current_run=helpers.utctimestamp(), status='Running')
mylar.SEARCH_STATUS = 'Running'
mylar.search.searchforissue()
helpers.job_management(write=True, job='Auto-Search', last_run_completed=helpers.utctimestamp(), status='Waiting')
mylar.SEARCH_STATUS = 'Waiting'
#mylar.SCHED_SEARCH_LAST = helpers.now()
| 1,292 | Python | .py | 28 | 42.357143 | 122 | 0.733704 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,238 | versioncheck.py | evilhero_mylar/mylar/versioncheck.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import platform, subprocess, re, os, urllib2, tarfile
import mylar
from mylar import logger, version
import requests
import re
def runGit(args):
git_locations = []
if mylar.CONFIG.GIT_PATH is not None:
git_locations.append(mylar.CONFIG.GIT_PATH)
git_locations.append('git')
if platform.system().lower() == 'darwin':
git_locations.append('/usr/local/git/bin/git')
output = err = None
for cur_git in git_locations:
cmd = '%s %s' % (cur_git, args)
try:
#logger.debug('Trying to execute: %s with shell in %s' % (cmd, mylar.PROG_DIR))
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, cwd=mylar.PROG_DIR)
output, err = p.communicate()
#logger.debug('Git output: %s' % output)
except Exception as e:
logger.error('Command %s didn\'t work [%s]' % (cmd, e))
continue
else:
if all([err is not None, err != '']):
logger.error('Encountered error: %s' % err)
if 'not found' in output or "not recognized as an internal or external command" in output:
logger.error('[%s] Unable to find git with command: %s' % (output, cmd))
output = None
elif 'fatal:' in output or err:
logger.error('Error: %s' % err)
logger.error('Git returned bad info. Are you sure this is a git installation? [%s]' % output)
output = None
elif output:
break
return (output, err)
def getVersion():
if mylar.CONFIG.GIT_BRANCH is not None and mylar.CONFIG.GIT_BRANCH.startswith('win32build'):
mylar.INSTALL_TYPE = 'win'
# Don't have a way to update exe yet, but don't want to set VERSION to None
return 'Windows Install', 'None'
elif os.path.isdir(os.path.join(mylar.PROG_DIR, '.git')):
mylar.INSTALL_TYPE = 'git'
output, err = runGit('rev-parse HEAD')
if not output:
logger.error('Couldn\'t find latest installed version.')
cur_commit_hash = None
#branch_history, err = runGit("log --oneline --pretty=format:'%h - %ar - %s' -n 5")
#bh = []
#print ("branch_history: " + branch_history)
#bh.append(branch_history.split('\n'))
#print ("bh1: " + bh[0])
cur_commit_hash = str(output).strip()
if not re.match('^[a-z0-9]+$', cur_commit_hash):
logger.error('Output does not look like a hash, not using it')
cur_commit_hash = None
if mylar.CONFIG.GIT_BRANCH:
branch = mylar.CONFIG.GIT_BRANCH
else:
branch = None
branch_name, err = runGit('branch --contains %s' % cur_commit_hash)
if not branch_name:
logger.warn('Could not retrieve branch name [%s] from git. Defaulting to Master.' % branch)
branch = 'master'
else:
for line in branch_name.split('\n'):
if '*' in line:
branch = re.sub('[\*\n]','',line).strip()
break
if not branch and mylar.CONFIG.GIT_BRANCH:
logger.warn('Unable to retrieve branch name [%s] from git. Setting branch to configuration value of : %s' % (branch, mylar.CONFIG.GIT_BRANCH))
branch = mylar.CONFIG.GIT_BRANCH
if not branch:
logger.warn('Could not retrieve branch name [%s] from git. Defaulting to Master.' % branch)
branch = 'master'
else:
logger.info('Branch detected & set to : %s' % branch)
return cur_commit_hash, branch
else:
mylar.INSTALL_TYPE = 'source'
version_file = os.path.join(mylar.PROG_DIR, 'version.txt')
if not os.path.isfile(version_file):
current_version = None
else:
with open(version_file, 'r') as f:
current_version = f.read().strip(' \n\r')
if current_version:
if mylar.CONFIG.GIT_BRANCH:
logger.info('Branch detected & set to : ' + mylar.CONFIG.GIT_BRANCH)
return current_version, mylar.CONFIG.GIT_BRANCH
else:
logger.warn('No branch specified within config - will attempt to poll version from mylar')
try:
branch = version.MYLAR_VERSION
logger.info('Branch detected & set to : ' + branch)
except:
branch = 'master'
logger.info('Unable to detect branch properly - set branch in config.ini, currently defaulting to : ' + branch)
return current_version, branch
else:
if mylar.CONFIG.GIT_BRANCH:
logger.info('Branch detected & set to : ' + mylar.CONFIG.GIT_BRANCH)
return current_version, mylar.CONFIG.GIT_BRANCH
else:
logger.warn('No branch specified within config - will attempt to poll version from mylar')
try:
branch = version.MYLAR_VERSION
logger.info('Branch detected & set to : ' + branch)
except:
branch = 'master'
logger.info('Unable to detect branch properly - set branch in config.ini, currently defaulting to : ' + branch)
return current_version, branch
logger.warn('Unable to determine which commit is currently being run. Defaulting to Master branch.')
def checkGithub(current_version=None):
if current_version is None:
current_version = mylar.CURRENT_VERSION
# Get the latest commit available from github
url = 'https://api.github.com/repos/%s/mylar/commits/%s' % (mylar.CONFIG.GIT_USER, mylar.CONFIG.GIT_BRANCH)
try:
response = requests.get(url, verify=True)
git = response.json()
mylar.LATEST_VERSION = git['sha']
except Exception as e:
logger.warn('[ERROR] Could not get the latest commit from github: %s' % e)
mylar.COMMITS_BEHIND = 0
return mylar.CURRENT_VERSION
# See how many commits behind we are
if current_version is not None:
logger.fdebug('Comparing currently installed version [%s] with latest github version [%s]' % (current_version, mylar.LATEST_VERSION))
url = 'https://api.github.com/repos/%s/mylar/compare/%s...%s' % (mylar.CONFIG.GIT_USER, current_version, mylar.LATEST_VERSION)
try:
response = requests.get(url, verify=True)
git = response.json()
mylar.COMMITS_BEHIND = git['total_commits']
except Exception as e:
logger.warn('[ERROR] Could not get commits behind from github: %s' % e)
mylar.COMMITS_BEHIND = 0
return mylar.CURRENT_VERSION
if mylar.COMMITS_BEHIND >= 1:
logger.info('New version is available. You are %s commits behind' % mylar.COMMITS_BEHIND)
if mylar.CONFIG.AUTO_UPDATE is True:
mylar.SIGNAL = 'update'
elif mylar.COMMITS_BEHIND == 0:
logger.info('Mylar is up to date')
elif mylar.COMMITS_BEHIND == -1:
logger.info('You are running an unknown version of Mylar. Run the updater to identify your version')
else:
logger.info('You are running an unknown version of Mylar. Run the updater to identify your version')
return mylar.LATEST_VERSION
def update():
if mylar.INSTALL_TYPE == 'win':
logger.info('Windows .exe updating not supported yet.')
pass
elif mylar.INSTALL_TYPE == 'git':
output, err = runGit('pull origin ' + mylar.CONFIG.GIT_BRANCH)
if output is None:
logger.error('Couldn\'t download latest version')
return
for line in output.split('\n'):
if 'Already up-to-date.' in line:
logger.info('No update available, not updating')
logger.info('Output: ' + str(output))
elif line.endswith('Aborting.'):
logger.error('Unable to update from git: ' +line)
logger.info('Output: ' + str(output))
else:
tar_download_url = 'https://github.com/%s/mylar/tarball/%s' % (mylar.CONFIG.GIT_USER, mylar.CONFIG.GIT_BRANCH)
update_dir = os.path.join(mylar.PROG_DIR, 'update')
version_path = os.path.join(mylar.PROG_DIR, 'version.txt')
try:
logger.info('Downloading update from: ' + tar_download_url)
response = requests.get(tar_download_url, verify=True, stream=True)
except (IOError, urllib2.URLError):
logger.error("Unable to retrieve new version from " + tar_download_url + ", can't update")
return
#try sanitizing the name here...
download_name = mylar.CONFIG.GIT_BRANCH + '-github' #data.geturl().split('/')[-1].split('?')[0]
tar_download_path = os.path.join(mylar.PROG_DIR, download_name)
# Save tar to disk
with open(tar_download_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
# Extract the tar to update folder
logger.info('Extracting file' + tar_download_path)
tar = tarfile.open(tar_download_path)
tar.extractall(update_dir)
tar.close()
# Delete the tar.gz
logger.info('Deleting file' + tar_download_path)
os.remove(tar_download_path)
# Find update dir name
update_dir_contents = [x for x in os.listdir(update_dir) if os.path.isdir(os.path.join(update_dir, x))]
if len(update_dir_contents) != 1:
logger.error(u"Invalid update data, update failed: " +str(update_dir_contents))
return
content_dir = os.path.join(update_dir, update_dir_contents[0])
# walk temp folder and move files to main folder
for dirname, dirnames, filenames in os.walk(content_dir):
dirname = dirname[len(content_dir) +1:]
for curfile in filenames:
old_path = os.path.join(content_dir, dirname, curfile)
new_path = os.path.join(mylar.PROG_DIR, dirname, curfile)
if os.path.isfile(new_path):
os.remove(new_path)
os.renames(old_path, new_path)
# Update version.txt
try:
with open(version_path, 'w') as f:
f.write(str(mylar.LATEST_VERSION))
except IOError as e:
logger.error("Unable to write current version to version.txt, update not complete: %s" % ex(e))
return
def versionload():
mylar.CURRENT_VERSION, mylar.CONFIG.GIT_BRANCH = getVersion()
if mylar.CURRENT_VERSION is not None:
hash = mylar.CURRENT_VERSION[:7]
else:
hash = "unknown"
if mylar.CONFIG.GIT_BRANCH == 'master':
vers = 'M'
elif mylar.CONFIG.GIT_BRANCH == 'development':
vers = 'D'
else:
vers = 'NONE'
mylar.USER_AGENT = 'Mylar/' +str(hash) +'(' +vers +') +http://www.github.com/evilhero/mylar/'
logger.info('Version information: %s [%s]' % (mylar.CONFIG.GIT_BRANCH, mylar.CURRENT_VERSION))
if mylar.CONFIG.CHECK_GITHUB_ON_STARTUP:
try:
mylar.LATEST_VERSION = checkGithub() #(CURRENT_VERSION)
except:
mylar.LATEST_VERSION = mylar.CURRENT_VERSION
else:
mylar.LATEST_VERSION = mylar.CURRENT_VERSION
if mylar.CONFIG.AUTO_UPDATE:
if mylar.CURRENT_VERSION != mylar.LATEST_VERSION and mylar.INSTALL_TYPE != 'win' and mylar.COMMITS_BEHIND > 0:
logger.info('Auto-updating has been enabled. Attempting to auto-update.')
mylar.SIGNAL = 'update'
| 12,594 | Python | .py | 253 | 38.924901 | 162 | 0.603586 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,239 | Failed.py | evilhero_mylar/mylar/Failed.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
import mylar
from mylar import logger, db, updater, helpers, parseit, findcomicfeed, notifiers, rsscheck
import feedparser as feedparser
import urllib
import os, errno
import string
import sys
import getopt
import re
import time
import urlparse
from xml.dom.minidom import parseString
import urllib2
import email.utils
import datetime
class FailedProcessor(object):
""" Handles Failed downloads that are passed from SABnzbd thus far """
def __init__(self, nzb_name=None, nzb_folder=None, id=None, issueid=None, comicid=None, prov=None, queue=None, oneoffinfo=None):
"""
nzb_name : Full name of the nzb file that has returned as a fail.
nzb_folder: Full path to the folder of the failed download.
"""
self.nzb_name = nzb_name
self.nzb_folder = nzb_folder
#if nzb_folder: self.nzb_folder = nzb_folder
self.log = ""
self.id = id
if issueid:
self.issueid = issueid
else:
self.issueid = None
if comicid:
self.comicid = comicid
else:
self.comicid = None
if oneoffinfo:
self.oneoffinfo = oneoffinfo
else:
self.oneoffinfo = None
self.prov = prov
if queue: self.queue = queue
self.valreturn = []
def _log(self, message, level=logger): #.message):
"""
A wrapper for the internal logger which also keeps track of messages and saves them to a string
message: The string to log (unicode)
level: The log level to use (optional)
"""
self.log += message + '\n'
def Process(self):
module = '[FAILED-DOWNLOAD]'
myDB = db.DBConnection()
if self.nzb_name and self.nzb_folder:
self._log('Failed download has been detected: ' + self.nzb_name + ' in ' + self.nzb_folder)
#since this has already been passed through the search module, which holds the IssueID in the nzblog,
#let's find the matching nzbname and pass it the IssueID in order to mark it as Failed and then return
#to the search module and continue trucking along.
nzbname = self.nzb_name
#remove extensions from nzb_name if they somehow got through (Experimental most likely)
extensions = ('.cbr', '.cbz')
if nzbname.lower().endswith(extensions):
fd, ext = os.path.splitext(nzbname)
self._log("Removed extension from nzb: " + ext)
nzbname = re.sub(str(ext), '', str(nzbname))
#replace spaces
nzbname = re.sub(' ', '.', str(nzbname))
nzbname = re.sub('[\,\:\?\'\(\)]', '', str(nzbname))
nzbname = re.sub('[\&]', 'and', str(nzbname))
nzbname = re.sub('_', '.', str(nzbname))
logger.fdebug(module + ' After conversions, nzbname is : ' + str(nzbname))
self._log("nzbname: " + str(nzbname))
nzbiss = myDB.selectone("SELECT * from nzblog WHERE nzbname=?", [nzbname]).fetchone()
if nzbiss is None:
self._log("Failure - could not initially locate nzbfile in my database to rename.")
logger.fdebug(module + ' Failure - could not locate nzbfile initially')
# if failed on spaces, change it all to decimals and try again.
nzbname = re.sub('_', '.', str(nzbname))
self._log("trying again with this nzbname: " + str(nzbname))
logger.fdebug(module + ' Trying to locate nzbfile again with nzbname of : ' + str(nzbname))
nzbiss = myDB.selectone("SELECT * from nzblog WHERE nzbname=?", [nzbname]).fetchone()
if nzbiss is None:
logger.error(module + ' Unable to locate downloaded file to rename. PostProcessing aborted.')
self._log('Unable to locate downloaded file to rename. PostProcessing aborted.')
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
else:
self._log("I corrected and found the nzb as : " + str(nzbname))
logger.fdebug(module + ' Auto-corrected and found the nzb as : ' + str(nzbname))
issueid = nzbiss['IssueID']
else:
issueid = nzbiss['IssueID']
logger.fdebug(module + ' Issueid: ' + str(issueid))
sarc = nzbiss['SARC']
#use issueid to get publisher, series, year, issue number
else:
issueid = self.issueid
nzbiss = myDB.selectone("SELECT * from nzblog WHERE IssueID=?", [issueid]).fetchone()
if nzbiss is None:
logger.info(module + ' Cannot locate corresponding record in download history. This will be implemented soon.')
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
nzbname = nzbiss['NZBName']
# find the provider.
self.prov = nzbiss['PROVIDER']
logger.info(module + ' Provider: ' + self.prov)
# grab the id.
self.id = nzbiss['ID']
logger.info(module + ' ID: ' + self.id)
annchk = "no"
if 'annual' in nzbname.lower():
logger.info(module + ' Annual detected.')
annchk = "yes"
issuenzb = myDB.selectone("SELECT * from annuals WHERE IssueID=? AND ComicName NOT NULL", [issueid]).fetchone()
else:
issuenzb = myDB.selectone("SELECT * from issues WHERE IssueID=? AND ComicName NOT NULL", [issueid]).fetchone()
if issuenzb is not None:
logger.info(module + ' issuenzb found.')
if helpers.is_number(issueid):
sandwich = int(issuenzb['IssueID'])
else:
logger.info(module + ' issuenzb not found.')
#if it's non-numeric, it contains a 'G' at the beginning indicating it's a multi-volume
#using GCD data. Set sandwich to 1 so it will bypass and continue post-processing.
if 'S' in issueid:
sandwich = issueid
elif 'G' in issueid or '-' in issueid:
sandwich = 1
try:
if helpers.is_number(sandwich):
if sandwich < 900000:
# if sandwich is less than 900000 it's a normal watchlist download. Bypass.
pass
else:
logger.info('Failed download handling for story-arcs and one-off\'s are not supported yet. Be patient!')
self._log(' Unable to locate downloaded file to rename. PostProcessing aborted.')
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
except NameError:
logger.info('sandwich was not defined. Post-processing aborted...')
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
comicid = issuenzb['ComicID']
issuenumOG = issuenzb['Issue_Number']
logger.info(module + ' Successfully detected as : ' + issuenzb['ComicName'] + ' issue: ' + str(issuenzb['Issue_Number']) + ' that was downloaded using ' + self.prov)
self._log('Successfully detected as : ' + issuenzb['ComicName'] + ' issue: ' + str(issuenzb['Issue_Number']) + ' downloaded using ' + self.prov)
logger.info(module + ' Marking as a Failed Download.')
self._log('Marking as a Failed Download.')
ctrlVal = {"IssueID": issueid}
Vals = {"Status": 'Failed'}
myDB.upsert("issues", Vals, ctrlVal)
ctrlVal = {"ID": self.id,
"Provider": self.prov,
"NZBName": nzbname}
Vals = {"Status": 'Failed',
"ComicName": issuenzb['ComicName'],
"Issue_Number": issuenzb['Issue_Number'],
"IssueID": issueid,
"ComicID": comicid,
"DateFailed": helpers.now()}
myDB.upsert("failed", Vals, ctrlVal)
logger.info(module + ' Successfully marked as Failed.')
self._log('Successfully marked as Failed.')
if mylar.CONFIG.FAILED_AUTO:
logger.info(module + ' Sending back to search to see if we can find something that will not fail.')
self._log('Sending back to search to see if we can find something better that will not fail.')
self.valreturn.append({"self.log": self.log,
"mode": 'retry',
"issueid": issueid,
"comicid": comicid,
"comicname": issuenzb['ComicName'],
"issuenumber": issuenzb['Issue_Number'],
"annchk": annchk})
return self.queue.put(self.valreturn)
else:
logger.info(module + ' Stopping search here as automatic handling of failed downloads is not enabled *hint*')
self._log('Stopping search here as automatic handling of failed downloads is not enabled *hint*')
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
def failed_check(self):
#issueid = self.issueid
#comicid = self.comicid
# ID = ID passed by search upon a match upon preparing to send it to client to download.
# ID is provider dependent, so the same file should be different for every provider.
module = '[FAILED_DOWNLOAD_CHECKER]'
myDB = db.DBConnection()
# Querying on NZBName alone will result in all downloads regardless of provider.
# This will make sure that the files being downloaded are different regardless of provider.
# Perhaps later improvement might be to break it down by provider so that Mylar will attempt to
# download same issues on different providers (albeit it shouldn't matter, if it's broke it's broke).
logger.info('prov : ' + str(self.prov) + '[' + str(self.id) + ']')
# if this is from nzbhydra, we need to rejig the id line so that the searchid is removed since it's always unique to the search.
if 'indexerguid' in self.id:
st = self.id.find('searchid:')
end = self.id.find(',',st)
self.id = '%' + self.id[:st] + '%' + self.id[end+1:len(self.id)-1] + '%'
chk_fail = myDB.selectone('SELECT * FROM failed WHERE ID LIKE ?', [self.id]).fetchone()
else:
chk_fail = myDB.selectone('SELECT * FROM failed WHERE ID=?', [self.id]).fetchone()
if chk_fail is None:
logger.info(module + ' Successfully marked this download as Good for downloadable content')
return 'Good'
else:
if chk_fail['status'] == 'Good':
logger.info(module + ' result has a status of GOOD - which means it does not currently exist in the failed download list.')
return chk_fail['status']
elif chk_fail['status'] == 'Failed':
logger.info(module + ' result has a status of FAIL which indicates it is not a good choice to download.')
logger.info(module + ' continuing search for another download.')
return chk_fail['status']
elif chk_fail['status'] == 'Retry':
logger.info(module + ' result has a status of RETRY which indicates it was a failed download that retried .')
return chk_fail['status']
elif chk_fail['status'] == 'Retrysame':
logger.info(module + ' result has a status of RETRYSAME which indicates it was a failed download that retried the initial download.')
return chk_fail['status']
else:
logger.info(module + ' result has a status of ' + chk_fail['status'] + '. I am not sure what to do now.')
return "nope"
def markFailed(self):
#use this to forcibly mark a single issue as being Failed (ie. if a search result is sent to a client, but the result
#ends up passing in a 404 or something that makes it so that the download can't be initiated).
module = '[FAILED-DOWNLOAD]'
myDB = db.DBConnection()
logger.info(module + ' Marking as a Failed Download.')
logger.fdebug(module + 'nzb_name: ' + self.nzb_name)
logger.fdebug(module + 'issueid: ' + str(self.issueid))
logger.fdebug(module + 'nzb_id: ' + str(self.id))
logger.fdebug(module + 'prov: ' + self.prov)
logger.fdebug('oneoffinfo: ' + str(self.oneoffinfo))
if self.oneoffinfo:
ComicName = self.oneoffinfo['ComicName']
IssueNumber = self.oneoffinfo['IssueNumber']
else:
if 'annual' in self.nzb_name.lower():
logger.info(module + ' Annual detected.')
annchk = "yes"
issuenzb = myDB.selectone("SELECT * from annuals WHERE IssueID=? AND ComicName NOT NULL", [self.issueid]).fetchone()
else:
issuenzb = myDB.selectone("SELECT * from issues WHERE IssueID=? AND ComicName NOT NULL", [self.issueid]).fetchone()
ctrlVal = {"IssueID": self.issueid}
Vals = {"Status": 'Failed'}
myDB.upsert("issues", Vals, ctrlVal)
ComicName = issuenzb['ComicName']
IssueNumber = issuenzb['Issue_Number']
ctrlVal = {"ID": self.id,
"Provider": self.prov,
"NZBName": self.nzb_name}
Vals = {"Status": 'Failed',
"ComicName": ComicName,
"Issue_Number": IssueNumber,
"IssueID": self.issueid,
"ComicID": self.comicid,
"DateFailed": helpers.now()}
myDB.upsert("failed", Vals, ctrlVal)
logger.info(module + ' Successfully marked as Failed.')
| 15,082 | Python | .py | 275 | 42.4 | 173 | 0.583655 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,240 | maintenance.py | evilhero_mylar/mylar/maintenance.py | # This file is part of Mylar.
# -*- coding: utf-8 -*-
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import threading
import sqlite3
import json
import mylar
from mylar import logger, importer
class Maintenance(object):
def __init__(self, mode, file=None, output=None):
self.mode = mode
self.maintenance_db = os.path.join(mylar.DATA_DIR, '.mylar_maintenance.db')
if self.mode == 'database-import':
self.dbfile = file
else:
self.dbfile = mylar.DB_FILE
self.file = file
self.outputfile = output
self.comiclist = []
self.maintenance_success = []
self.maintenance_fail = []
def sql_attachmylar(self):
self.connectmylar = sqlite3.connect(self.dbfile)
self.dbmylar = self.connectmylar.cursor()
def sql_closemylar(self):
self.connectmylar.commit()
self.dbmylar.close()
def sql_attach(self):
self.conn = sqlite3.connect(self.maintenance_db)
self.db = self.conn.cursor()
self.db.execute('CREATE TABLE IF NOT EXISTS maintenance (id TEXT, mode TEXT, status TEXT, progress TEXT, total TEXT, current TEXT, last_comicid TEXT, last_series TEXT, last_seriesyear TEXT)')
def sql_close(self):
self.conn.commit()
self.db.close()
def database_import(self):
self.sql_attachmylar()
comicidlist = self.dbmylar.execute('SELECT * FROM comics')
for i in comicidlist:
self.comiclist.append(i['ComicID'])
self.sql_closemylar()
self.importIT()
def json_import(self):
self.comiclist = json.load(open(self.file))
logger.info('[MAINTENANCE-MODE][JSON-IMPORT] Found %s series within json listing. Preparing to mass import to existing db.' % (len(self.comiclist)))
self.importIT()
def json_export(self):
self.sql_attachmylar()
for i in self.dbmylar.execute('SELECT ComicID FROM comics'):
self.comiclist.append({'ComicID': i[0]})
self.sql_closemylar()
with open(self.outputfile, 'wb') as outfile:
json.dump(self.comiclist, outfile)
logger.info('[MAINTENANCE-MODE][%s] Successfully exported %s ComicID\'s to json file: %s' % (self.mode.upper(), len(self.comiclist), self.outputfile))
def fix_slashes(self):
self.sql_attachmylar()
for ct in self.dbmylar.execute("SELECT ComicID, ComicLocation FROM comics WHERE ComicLocation like ?", ['%' + os.sep.encode('unicode-escape') + os.sep.encode('unicode-escape') + '%']):
st = ct[1].find(os.sep.encode('unicode-escape')+os.sep.encode('unicode-escape'))
if st != -1:
rootloc = ct[1][:st]
clocation = ct[1][st+2:]
if clocation[0] != os.sep.encode('unicode-escape'):
new_path = os.path.join(rootloc, clocation)
logger.info('[Incorrect slashes in path detected for OS] %s' % os.path.join(rootloc, ct[1]))
logger.info('[PATH CORRECTION] %s' % new_path)
self.comiclist.append({'ComicLocation': new_path,
'ComicID': ct[0]})
for cm in self.comiclist:
try:
self.dbmylar.execute("UPDATE comics SET ComicLocation=? WHERE ComicID=?", (cm['ComicLocation'], cm['ComicID']))
except Exception as e:
logger.warn('Unable to correct entry: [ComicID:%s] %s [%e]' % (cm['ComicLocation'], cm['ComicID'],e))
self.sql_closemylar()
if len(self.comiclist) >0:
logger.info('[MAINTENANCE-MODE][%s] Successfully fixed the path slashes for %s series' % (self.mode.upper(), len(self.comiclist)))
else:
logger.info('[MAINTENANCE-MODE][%s] No series found with incorrect slashes in the path' % self.mode.upper())
def check_status(self):
try:
found = False
self.sql_attach()
checkm = self.db.execute('SELECT * FROM maintenance')
for cm in checkm:
found = True
if 'import' in cm[1]:
logger.info('[MAINTENANCE-MODE][STATUS] Current Progress: %s [%s / %s]' % (cm[2].upper(), cm[3], cm[4]))
if cm[2] == 'running':
try:
logger.info('[MAINTENANCE-MODE][STATUS] Current Import: %s' % (cm[5]))
if cm[6] is not None:
logger.info('[MAINTENANCE-MODE][STATUS] Last Successful Import: %s [%s]' % (cm[7], cm[6]))
except:
pass
elif cm[2] == 'completed':
logger.info('[MAINTENANCE-MODE][STATUS] Last Successful Import: %s [%s]' % (cm[7], cm[6]))
else:
logger.info('[MAINTENANCE-MODE][STATUS] Current Progress: %s [mode: %s]' % (cm[2].upper(), cm[1]))
if found is False:
raise Error
except Exception as e:
logger.info('[MAINTENANCE-MODE][STATUS] Nothing is currently running')
self.sql_close()
def importIT(self):
#set startup...
if len(self.comiclist) > 0:
self.sql_attach()
query = "DELETE FROM maintenance"
self.db.execute(query)
query = "INSERT INTO maintenance (id, mode, total, status) VALUES (%s,'%s',%s,'%s')" % ('1', self.mode, len(self.comiclist), "running")
self.db.execute(query)
self.sql_close()
logger.info('[MAINTENANCE-MODE][%s] Found %s series in previous db. Preparing to migrate into existing db.' % (self.mode.upper(), len(self.comiclist)))
count = 1
for x in self.comiclist:
logger.info('[MAINTENANCE-MODE][%s] [%s/%s] now attempting to add %s to watchlist...' % (self.mode.upper(), count, len(self.comiclist), x['ComicID']))
try:
self.sql_attach()
self.db.execute("UPDATE maintenance SET progress=?, total=?, current=? WHERE id='1'", (count, len(self.comiclist), re.sub('4050-', '', x['ComicID'].strip())))
self.sql_close()
except Exception as e:
logger.warn('[ERROR] %s' % e)
maintenance_info = importer.addComictoDB(re.sub('4050-', '', x['ComicID']).strip(), calledfrom='maintenance')
try:
logger.info('MAINTENANCE: %s' % maintenance_info)
if maintenance_info['status'] == 'complete':
logger.fdebug('[MAINTENANCE-MODE][%s] Successfully added %s [%s] to watchlist.' % (self.mode.upper(), maintenance_info['comicname'], maintenance_info['year']))
else:
logger.fdebug('[MAINTENANCE-MODE][%s] Unable to add %s [%s] to watchlist.' % (self.mode.upper(), maintenance_info['comicname'], maintenance_info['year']))
raise IOError
self.maintenance_success.append(x)
try:
self.sql_attach()
self.db.execute("UPDATE maintenance SET progress=?, last_comicid=?, last_series=?, last_seriesyear=? WHERE id='1'", (count, re.sub('4050-', '', x['ComicID'].strip()), maintenance_info['comicname'], maintenance_info['year']))
self.sql_close()
except Exception as e:
logger.warn('[ERROR] %s' % e)
except IOError as e:
logger.warn('[MAINTENANCE-MODE][%s] Unable to add series to watchlist: %s' % (self.mode.upper(), e))
self.maintenance_fail.append(x)
count+=1
else:
logger.warn('[MAINTENANCE-MODE][%s] Unable to locate any series in db. This is probably a FATAL error and an unrecoverable db.' % self.mode.upper())
return
logger.info('[MAINTENANCE-MODE][%s] Successfully imported %s series into existing db.' % (self.mode.upper(), len(self.maintenance_success)))
if len(self.maintenance_fail) > 0:
logger.info('[MAINTENANCE-MODE][%s] Failed to import %s series into existing db: %s' % (self.mode.upper(), len(self.maintenance_success), self.maintenance_fail))
try:
self.sql_attach()
self.db.execute("UPDATE maintenance SET status=? WHERE id='1'", ["completed"])
self.sql_close()
except Exception as e:
logger.warn('[ERROR] %s' % e)
| 9,190 | Python | .py | 165 | 43.163636 | 248 | 0.581007 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,241 | search.py | evilhero_mylar/mylar/search.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
import mylar
from mylar import logger, db, updater, helpers, parseit, findcomicfeed, notifiers, rsscheck, Failed, filechecker, auth32p, sabnzbd, nzbget, wwt, getcomics
import feedparser
import requests
import urllib
import os, errno
import string
import sys
import getopt
import re
import time
import urlparse
from urlparse import urljoin
from xml.dom.minidom import parseString
import urllib2
import email.utils
import datetime
import shutil
from base64 import b16encode, b32decode
from operator import itemgetter
from wsgiref.handlers import format_date_time
def search_init(ComicName, IssueNumber, ComicYear, SeriesYear, Publisher, IssueDate, StoreDate, IssueID, AlternateSearch=None, UseFuzzy=None, ComicVersion=None, SARC=None, IssueArcID=None, mode=None, rsscheck=None, ComicID=None, manualsearch=None, filesafe=None, allow_packs=None, oneoff=False, manual=False, torrentid_32p=None, digitaldate=None, booktype=None):
mylar.COMICINFO = []
unaltered_ComicName = None
if filesafe:
if filesafe != ComicName and mode != 'want_ann':
logger.info('[SEARCH] Special Characters exist within Series Title. Enabling search-safe Name : %s' % filesafe)
if AlternateSearch is None or AlternateSearch == 'None':
AlternateSearch = filesafe
else:
AlternateSearch += '##' + filesafe
unaltered_ComicName = ComicName
#ComicName = filesafe
#logger.info('AlternateSearch is : ' + AlternateSearch)
if ComicYear == None:
ComicYear = str(datetime.datetime.now().year)
else:
ComicYear = str(ComicYear)[:4]
if Publisher:
if Publisher == 'IDW Publishing':
Publisher = 'IDW'
logger.fdebug('Publisher is : %s' % Publisher)
if IssueArcID and not IssueID:
issuetitle = helpers.get_issue_title(IssueArcID)
else:
issuetitle = helpers.get_issue_title(IssueID)
if issuetitle:
logger.fdebug('Issue Title given as : %s' % issuetitle)
else:
logger.fdebug('Issue Title not found. Setting to None.')
if mode == 'want_ann':
logger.info("Annual/Special issue search detected. Appending to issue #")
#anything for mode other than None indicates an annual.
if all(['annual' not in ComicName.lower(), 'special' not in ComicName.lower()]):
ComicName = '%s Annual' % ComicName
if all([AlternateSearch is not None, AlternateSearch != "None", 'special' not in ComicName.lower()]):
AlternateSearch = '%s Annual' % AlternateSearch
if mode == 'pullwant' or IssueID is None:
#one-off the download.
logger.fdebug('One-Off Search parameters:')
logger.fdebug('ComicName: %s' % ComicName)
logger.fdebug('Issue: %s' % IssueNumber)
logger.fdebug('Year: %s' % ComicYear)
logger.fdebug('IssueDate: %s' % IssueDate)
oneoff = True
if SARC:
logger.fdebug("Story-ARC Search parameters:")
logger.fdebug("Story-ARC: %s" % SARC)
logger.fdebug("IssueArcID: %s" % IssueArcID)
torprovider = []
torp = 0
torznabs = 0
torznab_hosts = []
logger.fdebug("Checking for torrent enabled.")
checked_once = False
if mylar.CONFIG.ENABLE_TORRENT_SEARCH: #and mylar.CONFIG.ENABLE_TORRENTS:
if mylar.CONFIG.ENABLE_32P:
torprovider.append('32p')
torp+=1
if mylar.CONFIG.ENABLE_PUBLIC:
torprovider.append('public torrents')
torp+=1
if mylar.CONFIG.ENABLE_TORZNAB is True:
for torznab_host in mylar.CONFIG.EXTRA_TORZNABS:
if torznab_host[4] == '1' or torznab_host[4] == 1:
torznab_hosts.append(torznab_host)
torprovider.append('torznab: %s' % torznab_host[0])
torznabs+=1
##nzb provider selection##
##'dognzb' or 'nzb.su' or 'experimental'
nzbprovider = []
nzbp = 0
if mylar.CONFIG.NZBSU == True:
nzbprovider.append('nzb.su')
nzbp+=1
if mylar.CONFIG.DOGNZB == True:
nzbprovider.append('dognzb')
nzbp+=1
# --------
# Xperimental
if mylar.CONFIG.EXPERIMENTAL == True:
nzbprovider.append('experimental')
nzbp+=1
newznabs = 0
newznab_hosts = []
if mylar.CONFIG.NEWZNAB is True:
for newznab_host in mylar.CONFIG.EXTRA_NEWZNABS:
if newznab_host[5] == '1' or newznab_host[5] == 1:
newznab_hosts.append(newznab_host)
nzbprovider.append('newznab: %s' % newznab_host[0])
newznabs+=1
ddls = 0
ddlprovider = []
if mylar.CONFIG.ENABLE_DDL is True:
ddlprovider.append('DDL')
ddls+=1
logger.fdebug('nzbprovider(s): %s' % nzbprovider)
# --------
torproviders = torp + torznabs
logger.fdebug('There are %s torrent providers you have selected.' % torproviders)
torpr = torproviders - 1
if torpr < 0:
torpr = -1
providercount = int(nzbp + newznabs)
logger.fdebug('There are : %s nzb providers you have selected' % providercount)
if providercount > 0:
logger.fdebug('Usenet Retention : %s days' % mylar.CONFIG.USENET_RETENTION)
if ddls > 0:
logger.fdebug('there are %s Direct Download providers that are currently enabled.' % ddls)
findit = {}
findit['status'] = False
totalproviders = providercount + torproviders + ddls
if totalproviders == 0:
logger.error('[WARNING] You have %s search providers enabled. I need at least ONE provider to work. Aborting search.' % totalproviders)
findit['status'] = False
nzbprov = None
return findit, nzbprov
prov_order, torznab_info, newznab_info = provider_sequence(nzbprovider, torprovider, newznab_hosts, torznab_hosts, ddlprovider)
# end provider order sequencing
logger.fdebug('search provider order is %s' % prov_order)
#fix for issue dates between Nov-Dec/(Jan-Feb-Mar)
IssDt = str(IssueDate)[5:7]
if any([IssDt == "12", IssDt == "11", IssDt == "01", IssDt == "02", IssDt == "03"]):
IssDateFix = IssDt
else:
IssDateFix = "no"
if StoreDate is not None:
StDt = str(StoreDate)[5:7]
if any([StDt == "10", StDt == "12", StDt == "11", StDt == "01", StDt == "02", StDt == "03"]):
IssDateFix = StDt
searchcnt = 0
srchloop = 1
if rsscheck:
if mylar.CONFIG.ENABLE_RSS:
searchcnt = 1 # rss-only
else:
searchcnt = 0 # if it's not enabled, don't even bother.
else:
if mylar.CONFIG.ENABLE_RSS:
searchcnt = 2 # rss first, then api on non-matches
else:
searchcnt = 2 #set the searchcnt to 2 (api)
srchloop = 2 #start the counter at api, so it will exit without running RSS
if IssueNumber is not None:
intIss = helpers.issuedigits(IssueNumber)
iss = IssueNumber
if u'\xbd' in IssueNumber:
findcomiciss = '0.5'
elif u'\xbc' in IssueNumber:
findcomiciss = '0.25'
elif u'\xbe' in IssueNumber:
findcomiciss = '0.75'
elif u'\u221e' in IssueNumber:
#issnum = utf-8 will encode the infinity symbol without any help
findcomiciss = 'infinity' # set 9999999999 for integer value of issue
else:
findcomiciss = iss
#determine the amount of loops here
fcs = 0
c_alpha = None
dsp_c_alpha = None
c_number = None
c_num_a4 = None
while fcs < len(findcomiciss):
#take first occurance of alpha in string and carry it through
if findcomiciss[fcs].isalpha():
c_alpha = findcomiciss[fcs:].rstrip()
c_number = findcomiciss[:fcs].rstrip()
break
elif '.' in findcomiciss[fcs]:
c_number = findcomiciss[:fcs].rstrip()
c_num_a4 = findcomiciss[fcs+1:].rstrip()
#if decimal seperates numeric from alpha (ie - 7.INH)
#don't give calpha a value or else will seperate with a space further down
#assign it to dsp_c_alpha so that it can be displayed for debugging.
if not c_num_a4.isdigit():
dsp_c_alpha = c_num_a4
else:
c_number = str(c_number) + '.' + str(c_num_a4)
break
fcs+=1
logger.fdebug('calpha/cnumber: %s / %s' % (dsp_c_alpha, c_number))
if c_number is None:
c_number = findcomiciss # if it's None, means no special alphas or decimals
if '.' in c_number:
decst = c_number.find('.')
c_number = c_number[:decst].rstrip()
while (srchloop <= searchcnt):
#searchmodes:
# rss - will run through the built-cached db of entries
# api - will run through the providers via api (or non-api in the case of Experimental)
# the trick is if the search is done during an rss compare, it needs to exit when done.
# otherwise, the order of operations is rss feed check first, followed by api on non-results.
if srchloop == 1: searchmode = 'rss' #order of ops - this will be used first.
elif srchloop == 2: searchmode = 'api'
if '0-Day' in ComicName:
cmloopit = 1
else:
if booktype == 'One-Shot':
cmloopit = 4
elif len(c_number) == 1:
cmloopit = 3
elif len(c_number) == 2:
cmloopit = 2
else:
cmloopit = 1
if findit['status'] is True:
logger.fdebug('Found result on first run, exiting search module now.')
break
logger.fdebug('Initiating Search via : %s' % searchmode)
while (cmloopit >= 1):
prov_count = 0
if len(prov_order) == 1:
tmp_prov_count = 1
else:
tmp_prov_count = len(prov_order)
if cmloopit == 4:
IssueNumber = None
searchprov = None
while (tmp_prov_count > prov_count):
send_prov_count = tmp_prov_count - prov_count
newznab_host = None
torznab_host = None
if prov_order[prov_count] == 'DDL':
searchprov = 'DDL'
if prov_order[prov_count] == '32p':
searchprov = '32P'
elif prov_order[prov_count] == 'public torrents':
searchprov = 'Public Torrents'
elif 'torznab' in prov_order[prov_count]:
searchprov = 'torznab'
for nninfo in torznab_info:
if nninfo['provider'] == prov_order[prov_count]:
torznab_host = nninfo['info']
if torznab_host is None:
logger.fdebug('there was an error - torznab information was blank and it should not be.')
elif 'newznab' in prov_order[prov_count]:
#this is for newznab
searchprov = 'newznab'
for nninfo in newznab_info:
if nninfo['provider'] == prov_order[prov_count]:
newznab_host = nninfo['info']
if newznab_host is None:
logger.fdebug('there was an error - newznab information was blank and it should not be.')
else:
newznab_host = None
torznab_host = None
searchprov = prov_order[prov_count].lower()
if searchprov == 'dognzb' and mylar.CONFIG.DOGNZB == 0:
#since dognzb could hit the 50 daily api limit during the middle of a search run, check here on each pass to make
#sure it's not disabled (it gets auto-disabled on maxing out the API hits)
prov_count+=1
continue
elif all([searchprov == '32P', checked_once is True]) or all([searchprov == 'DDL', checked_once is True]) or all ([searchprov == 'Public Torrents', checked_once is True]) or all([searchprov == 'experimental', checked_once is True]) or all([searchprov == 'DDL', checked_once is True]):
prov_count+=1
continue
if searchmode == 'rss':
#if searchprov.lower() == 'ddl':
# prov_count+=1
# continue
findit = NZB_SEARCH(ComicName, IssueNumber, ComicYear, SeriesYear, Publisher, IssueDate, StoreDate, searchprov, send_prov_count, IssDateFix, IssueID, UseFuzzy, newznab_host, ComicVersion=ComicVersion, SARC=SARC, IssueArcID=IssueArcID, RSS="yes", ComicID=ComicID, issuetitle=issuetitle, unaltered_ComicName=unaltered_ComicName, oneoff=oneoff, cmloopit=cmloopit, manual=manual, torznab_host=torznab_host, digitaldate=digitaldate, booktype=booktype)
if findit['status'] is False:
if AlternateSearch is not None and AlternateSearch != "None":
chkthealt = AlternateSearch.split('##')
if chkthealt == 0:
AS_Alternate = AlternateSearch
loopit = len(chkthealt)
for calt in chkthealt:
AS_Alternate = re.sub('##', '', calt)
logger.info('Alternate Search pattern detected...re-adjusting to : %s' % AS_Alternate)
findit = NZB_SEARCH(AS_Alternate, IssueNumber, ComicYear, SeriesYear, Publisher, IssueDate, StoreDate, searchprov, send_prov_count, IssDateFix, IssueID, UseFuzzy, newznab_host, ComicVersion=ComicVersion, SARC=SARC, IssueArcID=IssueArcID, RSS="yes", ComicID=ComicID, issuetitle=issuetitle, unaltered_ComicName=AS_Alternate, allow_packs=allow_packs, oneoff=oneoff, cmloopit=cmloopit, manual=manual, torznab_host=torznab_host, digitaldate=digitaldate, booktype=booktype)
if findit['status'] is True:
break
if findit['status'] is True:
break
else:
logger.fdebug("findit = found!")
break
else:
findit = NZB_SEARCH(ComicName, IssueNumber, ComicYear, SeriesYear, Publisher, IssueDate, StoreDate, searchprov, send_prov_count, IssDateFix, IssueID, UseFuzzy, newznab_host, ComicVersion=ComicVersion, SARC=SARC, IssueArcID=IssueArcID, RSS="no", ComicID=ComicID, issuetitle=issuetitle, unaltered_ComicName=unaltered_ComicName, allow_packs=allow_packs, oneoff=oneoff, cmloopit=cmloopit, manual=manual, torznab_host=torznab_host, torrentid_32p=torrentid_32p, digitaldate=digitaldate, booktype=booktype)
if all([searchprov == '32P', checked_once is False]) or all([searchprov.lower() == 'ddl', checked_once is False]) or all([searchprov == 'Public Torrents', checked_once is False]) or all([searchprov == 'experimental', checked_once is False]):
checked_once = True
if findit['status'] is False:
if AlternateSearch is not None and AlternateSearch != "None":
chkthealt = AlternateSearch.split('##')
if chkthealt == 0:
AS_Alternate = AlternateSearch
loopit = len(chkthealt)
for calt in chkthealt:
AS_Alternate = re.sub('##', '', calt)
logger.info('Alternate Search pattern detected...re-adjusting to : %s' % AS_Alternate)
findit = NZB_SEARCH(AS_Alternate, IssueNumber, ComicYear, SeriesYear, Publisher, IssueDate, StoreDate, searchprov, send_prov_count, IssDateFix, IssueID, UseFuzzy, newznab_host, ComicVersion=ComicVersion, SARC=SARC, IssueArcID=IssueArcID, RSS="no", ComicID=ComicID, issuetitle=issuetitle, unaltered_ComicName=unaltered_ComicName, allow_packs=allow_packs, oneoff=oneoff, cmloopit=cmloopit, manual=manual, torznab_host=torznab_host, torrentid_32p=torrentid_32p, digitaldate=digitaldate, booktype=booktype)
if findit['status'] is True:
break
if findit['status'] is True:
break
else:
logger.fdebug("findit = found!")
break
if searchprov == 'newznab':
searchprov = newznab_host[0].rstrip()
elif searchprov == 'torznab':
searchprov = torznab_host[0].rstrip()
if manual is not True:
if IssueNumber is not None:
issuedisplay = IssueNumber
else:
if any([booktype == 'One-Shot', booktype == 'TPB']):
issuedisplay = None
else:
issuedisplay = StoreDate[5:]
if issuedisplay is None:
logger.info('Could not find %s (%s) using %s [%s]' % (ComicName, SeriesYear, searchprov, searchmode))
else:
logger.info('Could not find Issue %s of %s (%s) using %s [%s]' % (issuedisplay, ComicName, SeriesYear, searchprov, searchmode))
prov_count+=1
if findit['status'] is True:
if searchprov == 'newznab':
searchprov = newznab_host[0].rstrip() + ' (newznab)'
elif searchprov == 'torznab':
searchprov = torznab_host[0].rstrip() + ' (torznab)'
srchloop = 4
break
elif srchloop == 2 and (cmloopit -1 >= 1):
time.sleep(30) #pause for 30s to not hammmer api's
cmloopit-=1
srchloop+=1
if manual is True:
logger.info('I have matched %s files: %s' % (len(mylar.COMICINFO), mylar.COMICINFO))
return mylar.COMICINFO, 'None'
if findit['status'] is True:
#check for snatched_havetotal being enabled here and adjust counts now.
#IssueID being the catch/check for one-offs as they won't exist on the watchlist and error out otherwise.
if mylar.CONFIG.SNATCHED_HAVETOTAL and any([oneoff is False, IssueID is not None]):
logger.fdebug('Adding this to the HAVE total for the series.')
helpers.incr_snatched(ComicID)
if searchprov == 'Public Torrents' and mylar.TMP_PROV != searchprov:
searchprov = mylar.TMP_PROV
return findit, searchprov
else:
logger.fdebug('findit: %s' % findit)
#if searchprov == '32P':
# pass
if manualsearch is None:
logger.info('Finished searching via : %s. Issue not found - status kept as Wanted.' % searchmode)
else:
logger.fdebug('Could not find issue doing a manual search via : %s' % searchmode)
if searchprov == '32P':
if mylar.CONFIG.MODE_32P == 0:
return findit, 'None'
elif mylar.CONFIG.MODE_32P == 1 and searchmode == 'api':
return findit, 'None'
return findit, 'None'
def NZB_SEARCH(ComicName, IssueNumber, ComicYear, SeriesYear, Publisher, IssueDate, StoreDate, nzbprov, prov_count, IssDateFix, IssueID, UseFuzzy, newznab_host=None, ComicVersion=None, SARC=None, IssueArcID=None, RSS=None, ComicID=None, issuetitle=None, unaltered_ComicName=None, allow_packs=None, oneoff=False, cmloopit=None, manual=False, torznab_host=None, torrentid_32p=None, digitaldate=None, booktype=None):
if any([allow_packs is None, allow_packs == 'None', allow_packs == 0, allow_packs == '0']) and all([mylar.CONFIG.ENABLE_TORRENT_SEARCH, mylar.CONFIG.ENABLE_32P]):
allow_packs = False
elif any([allow_packs == 1, allow_packs == '1']) and all([mylar.CONFIG.ENABLE_TORRENT_SEARCH, mylar.CONFIG.ENABLE_32P]):
allow_packs = True
newznab_local = False
if nzbprov == 'nzb.su':
apikey = mylar.CONFIG.NZBSU_APIKEY
verify = bool(mylar.CONFIG.NZBSU_VERIFY)
elif nzbprov == 'dognzb':
apikey = mylar.CONFIG.DOGNZB_APIKEY
verify = bool(mylar.CONFIG.DOGNZB_VERIFY)
elif nzbprov == 'experimental':
apikey = 'none'
verify = False
elif nzbprov == 'torznab':
name_torznab = torznab_host[0].rstrip()
host_torznab = torznab_host[1].rstrip()
apikey = torznab_host[2].rstrip()
verify = False
category_torznab = torznab_host[3]
if any([category_torznab is None, category_torznab == 'None']):
category_torznab = '8020'
logger.fdebug('Using Torznab host of : %s' % name_torznab)
elif nzbprov == 'newznab':
#updated to include Newznab Name now
name_newznab = newznab_host[0].rstrip()
host_newznab = newznab_host[1].rstrip()
if name_newznab[-7:] == '[local]':
name_newznab = name_newznab[:-7].strip()
newznab_local = True
elif name_newznab[-10:] == '[nzbhydra]':
name_newznab = name_newznab[:-10].strip()
newznab_local = False
apikey = newznab_host[3].rstrip()
verify = bool(newznab_host[2])
if '#' in newznab_host[4].rstrip():
catstart = newznab_host[4].find('#')
category_newznab = newznab_host[4][catstart +1:]
logger.fdebug('Non-default Newznab category set to : %s' % category_newznab)
else:
category_newznab = '7030'
logger.fdebug('Using Newznab host of : %s' % name_newznab)
if RSS == "yes":
if 'newznab' in nzbprov:
tmpprov = '%s (%s) [RSS]' % (name_newznab, nzbprov)
elif 'torznab' in nzbprov:
tmpprov = '%s (%s) [RSS]' % (name_torznab, nzbprov)
else:
tmpprov = '%s [RSS]' % nzbprov
else:
if 'newznab' in nzbprov:
tmpprov = '%s (%s)' % (name_newznab, nzbprov)
elif 'torznab' in nzbprov:
tmpprov = '%s (%s)' % (name_torznab, nzbprov)
else:
tmpprov = nzbprov
if cmloopit == 4:
issuedisplay = None
logger.info('Shhh be very quiet...I\'m looking for %s (%s) using %s.' % (ComicName, ComicYear, tmpprov))
elif IssueNumber is not None:
issuedisplay = IssueNumber
else:
issuedisplay = StoreDate[5:]
if '0-Day Comics Pack' in ComicName:
logger.info('Shhh be very quiet...I\'m looking for %s using %s.' % (ComicName, tmpprov))
elif cmloopit != 4:
logger.info('Shhh be very quiet...I\'m looking for %s issue: %s (%s) using %s.' % (ComicName, issuedisplay, ComicYear, tmpprov))
#this will completely render the api search results empty. Needs to get fixed.
if mylar.CONFIG.PREFERRED_QUALITY == 0: filetype = ""
elif mylar.CONFIG.PREFERRED_QUALITY == 1: filetype = ".cbr"
elif mylar.CONFIG.PREFERRED_QUALITY == 2: filetype = ".cbz"
ci = ""
comsearch = []
isssearch = []
comyear = str(ComicYear)
#print ("-------SEARCH FOR MISSING------------------")
#ComicName is unicode - let's unicode and ascii it cause we'll be comparing filenames against it.
u_ComicName = ComicName.encode('ascii', 'replace').strip()
findcomic = u_ComicName
cm1 = re.sub("[\/\-]", " ", findcomic)
# replace whitespace in comic name with %20 for api search
#cm = re.sub("\&", "%26", str(cm1))
cm = re.sub("\\band\\b", "", cm1.lower()) # remove 'and' & '&' from the search pattern entirely (broader results, will filter out later)
cm = re.sub("\\bthe\\b", "", cm.lower()) # remove 'the' from the search pattern to accomodate naming differences
cm = re.sub("[\&\:\?\,]", "", str(cm))
cm = re.sub('\s+', ' ', cm)
cm = re.sub(" ", "%20", str(cm))
cm = re.sub("'", "%27", str(cm))
if IssueNumber is not None:
intIss = helpers.issuedigits(IssueNumber)
iss = IssueNumber
if u'\xbd' in IssueNumber:
findcomiciss = '0.5'
elif u'\xbc' in IssueNumber:
findcomiciss = '0.25'
elif u'\xbe' in IssueNumber:
findcomiciss = '0.75'
elif u'\u221e' in IssueNumber:
#issnum = utf-8 will encode the infinity symbol without any help
findcomiciss = 'infinity' # set 9999999999 for integer value of issue
else:
findcomiciss = iss
isssearch = str(findcomiciss)
else:
intIss = None
isssearch = None
findcomiciss = None
comsearch = cm
#origcmloopit = cmloopit
findcount = 1 # this could be a loop in the future possibly
findloop = 0
foundcomic = []
foundc = {}
foundc['status'] = False
done = False
seperatealpha = "no"
#---issue problem
# if issue is '011' instead of '11' in nzb search results, will not have same
# results. '011' will return different than '11', as will '009' and '09'.
while (findloop < findcount):
logger.fdebug('findloop: %s / findcount: %s' % (findloop, findcount))
comsrc = comsearch
if nzbprov == 'dognzb' and not mylar.CONFIG.DOGNZB:
foundc['status'] = False
done = True
break
if any([nzbprov == '32P', nzbprov == 'Public Torrents', nzbprov == 'ddl']):
#because 32p directly stores the exact issue, no need to worry about iterating over variations of the issue number.
findloop == 99
if done is True and seperatealpha == "no":
logger.fdebug("we should break out now - sucessful search previous")
findloop == 99
break
# here we account for issue pattern variations
if IssueNumber is not None:
if seperatealpha == "yes":
isssearch = str(c_number) + "%20" + str(c_alpha)
if cmloopit == 3:
comsearch = comsrc + "%2000" + str(isssearch) #+ "%20" + str(filetype)
issdig = '00'
elif cmloopit == 2:
comsearch = comsrc + "%200" + str(isssearch) #+ "%20" + str(filetype)
issdig = '0'
elif cmloopit == 1:
comsearch = comsrc + "%20" + str(isssearch) #+ "%20" + str(filetype)
issdig = ''
else:
foundc['status'] = False
done = True
break
mod_isssearch = str(issdig) + str(isssearch)
else:
if cmloopit == 4:
mod_isssearch = ''
else:
comsearch = StoreDate
mod_isssearch = StoreDate
#--- this is basically for RSS Feeds ---
#logger.fdebug('RSS Check: %s' % RSS)
#logger.fdebug('nzbprov: %s' % nzbprov)
#logger.fdebug('comicid: %s' % ComicID)
if nzbprov == 'ddl' and RSS == "no":
cmname = re.sub("%20", " ", str(comsrc))
logger.fdebug('Sending request to DDL site for : %s %s' % (findcomic, isssearch))
b = getcomics.GC(query='%s %s' % (findcomic, isssearch))
bb = b.search()
#logger.info('bb returned from DDL: %s' % bb)
elif RSS == "yes":
if nzbprov == 'ddl':
logger.fdebug('Sending request to [%s] RSS for %s : %s' % (nzbprov, ComicName, mod_isssearch))
bb = rsscheck.ddl_dbsearch(ComicName, mod_isssearch, ComicID, nzbprov, oneoff)
elif nzbprov == '32P' or nzbprov == 'Public Torrents':
cmname = re.sub("%20", " ", str(comsrc))
logger.fdebug('Sending request to [%s] RSS for %s : %s' % (nzbprov, ComicName, mod_isssearch))
bb = rsscheck.torrentdbsearch(ComicName, mod_isssearch, ComicID, nzbprov, oneoff)
else:
logger.fdebug('Sending request to RSS for %s : %s (%s)' % (findcomic, mod_isssearch, ComicYear))
if nzbprov == 'newznab':
nzbprov_fix = name_newznab
elif nzbprov == 'torznab':
nzbprov_fix = name_torznab
else: nzbprov_fix = nzbprov
bb = rsscheck.nzbdbsearch(findcomic, mod_isssearch, ComicID, nzbprov_fix, ComicYear, ComicVersion, oneoff)
if bb is None:
bb = 'no results'
#this is the API calls
else:
#32P is redudant now since only RSS works
# - just getting it ready for when it's not redudant :)
if nzbprov == '':
bb = "no results"
if nzbprov == '32P':
if all([mylar.CONFIG.MODE_32P == 1, mylar.CONFIG.ENABLE_32P is True]):
if ComicName[:17] == '0-Day Comics Pack':
searchterm = {'series': ComicName, 'issue': StoreDate[8:10], 'volume': StoreDate[5:7], 'torrentid_32p': None}
else:
searchterm = {'series': ComicName, 'id': ComicID, 'issue': findcomiciss, 'volume': ComicVersion, 'publisher': Publisher, 'torrentid_32p': torrentid_32p, 'booktype': booktype}
#first we find the id on the serieslist of 32P
#then we call the ajax against the id and issue# and volume (if exists)
a = auth32p.info32p(searchterm=searchterm)
bb = a.searchit()
if bb is None:
bb = 'no results'
else:
bb = "no results"
elif nzbprov == 'Public Torrents':
cmname = re.sub("%20", " ", str(comsrc))
logger.fdebug('Sending request to [WWT-SEARCH] for %s : %s' % (cmname, mod_isssearch))
ww = wwt.wwt(cmname, mod_isssearch)
bb = ww.wwt_connect()
#bb = rsscheck.torrents(pickfeed='TPSE-SEARCH', seriesname=cmname, issue=mod_isssearch)#cmname,issue=mod_isssearch)
if bb is None:
bb = 'no results'
elif nzbprov != 'experimental':
if nzbprov == 'dognzb':
findurl = "https://api.dognzb.cr/api?t=search&q=" + str(comsearch) + "&o=xml&cat=7030"
elif nzbprov == 'nzb.su':
findurl = "https://api.nzb.su/api?t=search&q=" + str(comsearch) + "&o=xml&cat=7030"
elif nzbprov == 'newznab':
#let's make sure the host has a '/' at the end, if not add it.
if host_newznab[len(host_newznab) -1:len(host_newznab)] != '/':
host_newznab_fix = str(host_newznab) + "/"
else: host_newznab_fix = host_newznab
findurl = str(host_newznab_fix) + "api?t=search&q=" + str(comsearch) + "&o=xml&cat=" + str(category_newznab)
elif nzbprov == 'torznab':
if host_torznab[len(host_torznab)-1:len(host_torznab)] == '/':
torznab_fix = host_torznab[:-1]
else:
torznab_fix = host_torznab
findurl = str(torznab_fix) + "?t=search&q=" + str(comsearch)
if category_torznab is not None:
findurl += "&cat=" + str(category_torznab)
else:
logger.warn('You have a blank newznab entry within your configuration. Remove it, save the config and restart mylar to fix things. Skipping this blank provider until fixed.')
findurl = None
bb = "noresults"
if findurl:
# helper function to replace apikey here so we avoid logging it ;)
findurl = findurl + "&apikey=" + str(apikey)
logsearch = helpers.apiremove(str(findurl), 'nzb')
### IF USENET_RETENTION is set, honour it
### For newznab sites, that means appending "&maxage=<whatever>" on the URL
if mylar.CONFIG.USENET_RETENTION != None and nzbprov != 'torznab':
findurl = findurl + "&maxage=" + str(mylar.CONFIG.USENET_RETENTION)
#set a delay between searches here. Default is for 30 seconds...
#changing this to lower could result in a ban from your nzb source due to hammering.
if mylar.CONFIG.SEARCH_DELAY == 'None' or mylar.CONFIG.SEARCH_DELAY is None:
pause_the_search = 30 # (it's in seconds)
elif str(mylar.CONFIG.SEARCH_DELAY).isdigit() and manual is False:
pause_the_search = int(mylar.CONFIG.SEARCH_DELAY) * 60
else:
logger.info("Check Search Delay - invalid numerical given. Force-setting to 30 seconds.")
pause_the_search = 30
#bypass for local newznabs
#remove the protocol string (http/https)
localbypass = False
if nzbprov == 'newznab':
if host_newznab_fix.startswith('http'):
hnc = host_newznab_fix.replace('http://', '')
elif host_newznab_fix.startswith('https'):
hnc = host_newznab_fix.replace('https://', '')
else:
hnc = host_newznab_fix
if any([hnc[:3] == '10.', hnc[:4] == '172.', hnc[:4] == '192.', hnc.startswith('localhost'), newznab_local is True]) and newznab_local != False:
logger.info('local domain bypass for %s is active.' % name_newznab)
localbypass = True
if localbypass == False:
logger.info('Pausing for %s seconds before continuing to avoid hammering' % pause_the_search)
#time.sleep(pause_the_search)
# Add a user-agent
headers = {'User-Agent': str(mylar.USER_AGENT)}
payload = None
if findurl.startswith('https:') and verify == False:
try:
from requests.packages.urllib3 import disable_warnings
disable_warnings()
except:
logger.warn('Unable to disable https warnings. Expect some spam if using https nzb providers.')
elif findurl.startswith('http:') and verify == True:
verify = False
#logger.fdebug('[SSL: ' + str(verify) + '] Search URL: ' + findurl)
logger.fdebug('[SSL: %s] Search URL: %s' % (verify, logsearch))
try:
r = requests.get(findurl, params=payload, verify=verify, headers=headers)
except requests.exceptions.Timeout as e:
logger.warn('Timeout occured fetching data from %s: %s' % (nzbprov, e))
foundc['status'] = False
break
except requests.exceptions.ConnectionError as e:
logger.warn('Connection error trying to retrieve data from %s: %s' % (nzbprov, e))
foundc['status'] = False
break
except requests.exceptions.RequestException as e:
logger.warn('General Error fetching data from %s: %s' % (nzbprov, e))
if str(r.status_code) == '503':
#HTTP Error 503
logger.warn('Aborting search due to Provider unavailability')
foundc['status'] = False
break
try:
if str(r.status_code) != '200':
logger.warn('Unable to retrieve search results from %s [Status Code returned: %s]' % (tmpprov, r.status_code))
if str(r.status_code) == '503':
logger.warn('Unavailable indexer detected. Disabling for a short duration and will try again.')
helpers.disable_provider(tmpprov)
data = False
else:
data = r.content
except:
data = False
if data:
bb = feedparser.parse(data)
else:
bb = "no results"
try:
if bb == 'no results':
logger.fdebug('No results for search query from %s' % tmpprov)
break
elif bb['feed']['error']:
logger.error('[ERROR CODE: %s] %s' % (bb['feed']['error']['code'], bb['feed']['error']['description']))
if bb['feed']['error']['code'] == '910':
logger.warn('DAILY API limit reached. Disabling provider usage until 12:01am')
mylar.CONFIG.DOGNZB = 0
foundc['status'] = False
done = True
else:
logger.warn('API Error. Check the error message and take action if required.')
foundc['status'] = False
done = True
break
except:
logger.info('no errors on data retrieval...proceeding')
pass
elif nzbprov == 'experimental':
#bb = parseit.MysterBinScrape(comsearch[findloop], comyear)
logger.info('sending %s to experimental search' % findcomic)
bb = findcomicfeed.Startit(findcomic, isssearch, comyear, ComicVersion, IssDateFix, booktype)
# since the regexs in findcomicfeed do the 3 loops, lets force the exit after
cmloopit == 1
done = False
log2file = ""
pack0day = False
pack_warning = False
if not bb == "no results":
for entry in bb['entries']:
#logger.fdebug('entry: %s' % entry) #<--- uncomment this to see what the search result(s) are
#brief match here against 32p since it returns the direct issue number
if nzbprov == '32P' and entry['title'][:17] == '0-Day Comics Pack':
logger.info('[32P-0DAY] 0-Day Comics Pack Discovered. Analyzing the pack info...')
if len(bb['entries']) == 1 or pack0day is True:
logger.info('[32P-0DAY] Only one pack for the week available. Selecting this by default.')
else:
logger.info('[32P-0DAY] More than one pack for the week is available...')
logger.info('bb-entries: %s' % bb['entries'])
if bb['entries'][1]['int_pubdate'] >= bb['int_pubdate']:
logger.info('[32P-0DAY] 2nd Pack is newest. Snatching that...')
pack0day = True
continue
elif nzbprov == '32P' and RSS == 'no':
if entry['pack'] == '0':
if helpers.issuedigits(entry['issues']) == intIss:
logger.fdebug('32P direct match to issue # : %s' % entry['issues'])
else:
logger.fdebug('The search result issue [%s] does not match up for some reason to our search result [%s]' % (entry['issues'], findcomiciss))
continue
elif any([entry['pack'] == '1', entry['pack'] == '2']) and allow_packs is False:
if pack_warning is False:
logger.fdebug('(possibly more than one) Pack detected, but option not enabled for this series. Ignoring subsequent pack results (to enable: on the series details page -> Edit Settings -> Enable Pack Downloads)')
pack_warning = True
continue
logger.fdebug("checking search result: %s" % entry['title'])
#some nzbsites feel that comics don't deserve a nice regex to strip the crap from the header, the end result is that we're
#dealing with the actual raw header which causes incorrect matches below.
#this is a temporary cut from the experimental search option (findcomicfeed) as it does this part well usually.
except_list=['releases', 'gold line', 'distribution', '0-day', '0 day']
splitTitle = entry['title'].split("\"")
_digits = re.compile('\d')
ComicTitle = entry['title']
for subs in splitTitle:
logger.fdebug('sub: %s' % subs)
regExCount = 0
try:
if len(subs) >= len(ComicName.split()) and not any(d in subs.lower() for d in except_list) and bool(_digits.search(subs)) is True:
if subs.lower().startswith('for'):
if ComicName.lower().startswith('for'):
pass
else:
#this is the crap we ignore. Continue (commented else, as it spams the logs)
#logger.fdebug('this starts with FOR : ' + str(subs) + '. This is not present in the series - ignoring.')
continue
logger.fdebug('Detected crap within header. Ignoring this portion of the result in order to see if it\'s a valid match.')
ComicTitle = subs
break
except:
break
comsize_m = 0
if nzbprov != "dognzb":
#rss for experimental doesn't have the size constraints embedded. So we do it here.
if RSS == "yes":
if nzbprov == '32P':
try:
#newer rss feeds will now return filesize from 32p. Safe-guard it incase it's an older result
comsize_b = entry['length']
except:
comsize_b = None
elif nzbprov == 'Public Torrents':
comsize_b = entry['length']
else:
comsize_b = entry['length']
else:
#Experimental already has size constraints done.
if nzbprov == '32P':
comsize_b = entry['filesize'] #None
elif nzbprov == 'Public Torrents':
comsize_b = entry['size']
elif nzbprov == 'experimental':
comsize_b = entry['length'] # we only want the size from the rss - the search/api has it already.
else:
try:
if entry['site'] == 'WWT':
comsize_b = entry['size']
elif entry['site'] == 'DDL':
comsize_b = helpers.human2bytes(entry['size'])
except Exception as e:
tmpsz = entry.enclosures[0]
comsize_b = tmpsz['length']
logger.fdebug('comsize_b: %s' % comsize_b)
#file restriction limitation here
#only works with TPSE (done here) & 32P (done in rsscheck) & Experimental (has it embeded in search and rss checks)
if nzbprov == 'Public Torrents' or (nzbprov == '32P' and RSS == 'no' and entry['title'][:17] != '0-Day Comics Pack'):
if nzbprov == 'Public Torrents':
if 'cbr' in entry['title'].lower():
format_type = 'cbr'
elif 'cbz' in entry['title'].lower():
format_type = 'cbz'
else:
format_type = 'unknown'
else:
if 'cbr' in entry['format']:
format_type = 'cbr'
elif 'cbz' in entry['format']:
format_type = 'cbz'
else:
format_type = 'unknown'
if mylar.CONFIG.PREFERRED_QUALITY == 1:
if format_type == 'cbr':
logger.fdebug('Quality restriction enforced [ .cbr only ]. Accepting result.')
else:
logger.fdebug('Quality restriction enforced [ .cbr only ]. Rejecting this result.')
continue
elif mylar.CONFIG.PREFERRED_QUALITY == 2:
if format_type == 'cbz':
logger.fdebug('Quality restriction enforced [ .cbz only ]. Accepting result.')
else:
logger.fdebug('Quality restriction enforced [ .cbz only ]. Rejecting this result.')
continue
if comsize_b is None or comsize_b == '0':
logger.fdebug('Size of file cannot be retrieved. Ignoring size-comparison and continuing.')
#comsize_b = 0
else:
if entry['title'][:17] != '0-Day Comics Pack':
comsize_m = helpers.human_size(comsize_b)
logger.fdebug('size given as: %s' % comsize_m)
#----size constraints.
#if it's not within size constaints - dump it now and save some time.
if mylar.CONFIG.USE_MINSIZE:
conv_minsize = helpers.human2bytes(mylar.CONFIG.MINSIZE + "M")
logger.fdebug('comparing Min threshold %s .. to .. nzb %s' % (conv_minsize, comsize_b))
if int(conv_minsize) > int(comsize_b):
logger.fdebug('Failure to meet the Minimum size threshold - skipping')
continue
if mylar.CONFIG.USE_MAXSIZE:
conv_maxsize = helpers.human2bytes(mylar.CONFIG.MAXSIZE + "M")
logger.fdebug('comparing Max threshold %s .. to .. nzb %s' % (conv_maxsize, comsize_b))
if int(comsize_b) > int(conv_maxsize):
logger.fdebug('Failure to meet the Maximium size threshold - skipping')
continue
#---- date constaints.
# if the posting date is prior to the publication date, dump it and save the time.
#logger.fdebug('entry: %s' % entry)
if nzbprov == 'experimental' or nzbprov =='32P':
pubdate = entry['pubdate']
else:
try:
pubdate = entry['updated']
except:
try:
pubdate = entry['pubdate']
except:
logger.fdebug('invalid date found. Unable to continue - skipping result.')
continue
if UseFuzzy == "1":
logger.fdebug('Year has been fuzzied for this series, ignoring store date comparison entirely.')
postdate_int = None
issuedate_int = None
else:
#use store date instead of publication date for comparisons since publication date is usually +2 months
if StoreDate is None or StoreDate == '0000-00-00':
if IssueDate is None or IssueDate == '0000-00-00':
logger.fdebug('Invalid store date & issue date detected - you probably should refresh the series or wait for CV to correct the data')
continue
else:
stdate = IssueDate
logger.fdebug('issue date used is : %s' % stdate)
else:
stdate = StoreDate
logger.fdebug('store date used is : %s' % stdate)
logger.fdebug('date used is : %s' % stdate)
postdate_int = None
if all([nzbprov == '32P', RSS == 'no']) or all([nzbprov == 'ddl', len(pubdate) == 10]):
postdate_int = pubdate
logger.fdebug('[%s] postdate_int: %s' % (nzbprov, postdate_int))
elif any([postdate_int is None, type(postdate_int) != int]) or not all([nzbprov == '32P', RSS == 'no']):
# convert it to a tuple
dateconv = email.utils.parsedate_tz(pubdate)
if all([nzbprov == '32P', dateconv is None, RSS == 'no']):
try:
pubdate = email.utils.formatdate(entry['int_pubdate'], localtime=True, usegmt=False)
except:
logger.warn('Unable to parsedate to a long-date that I can undestand : %s' % entry['int_pubdate'])
else:
logger.fdebug('Successfully converted to : %s' % pubdate)
dateconv = email.utils.parsedate_tz(pubdate)
try:
dateconv2 = datetime.datetime(*dateconv[:6])
except TypeError as e:
logger.warn('Unable to convert timestamp from : %s [%s]' % ((dateconv,), e))
try:
# convert it to a numeric time, then subtract the timezone difference (+/- GMT)
if dateconv[-1] is not None:
postdate_int = time.mktime(dateconv[:len(dateconv) -1]) - dateconv[-1]
else:
postdate_int = time.mktime(dateconv[:len(dateconv) -1])
except:
logger.warn('Unable to parse posting date from provider result set for : %s' % entry['title'])
continue
if all([digitaldate != '0000-00-00', digitaldate is not None]):
i = 0
else:
digitaldate_int = '00000000'
i = 1
while i <= 1:
if i == 0:
usedate = digitaldate
else:
usedate = stdate
logger.fdebug('usedate: %s' % usedate)
#convert it to a Thu, 06 Feb 2014 00:00:00 format
issue_converted = datetime.datetime.strptime(usedate.rstrip(), '%Y-%m-%d')
issue_convert = issue_converted + datetime.timedelta(days=-1)
# to get past different locale's os-dependent dates, let's convert it to a generic datetime format
try:
stamp = time.mktime(issue_convert.timetuple())
issconv = format_date_time(stamp)
except OverflowError:
logger.fdebug('Error attempting to convert the timestamp into a generic format. Probably due to the epoch limiation.')
issconv = issue_convert.strftime('%a, %d %b %Y %H:%M:%S')
#convert it to a tuple
econv = email.utils.parsedate_tz(issconv)
econv2 = datetime.datetime(*econv[:6])
#convert it to a numeric and drop the GMT/Timezone
try:
usedate_int = time.mktime(econv[:len(econv) -1])
except OverflowError:
logger.fdebug('Unable to convert timestamp to integer format. Forcing things through.')
isyear = econv[1]
epochyr = '1970'
if int(isyear) <= int(epochyr):
tm = datetime.datetime(1970, 1, 1)
usedate_int = int(time.mktime(tm.timetuple()))
else:
continue
if i == 0:
digitaldate_int = usedate_int
digconv2 = econv2
else:
issuedate_int = usedate_int
issconv2 = econv2
i+=1
try:
#try new method to get around issues populating in a diff timezone thereby putting them in a different day.
#logger.info('digitaldate: %s' % digitaldate)
#logger.info('dateconv2: %s' % dateconv2.date())
#logger.info('digconv2: %s' % digconv2.date())
if digitaldate != '0000-00-00' and dateconv2.date() >= digconv2.date():
logger.fdebug('%s is after DIGITAL store date of %s' % (pubdate, digitaldate))
elif dateconv2.date() < issconv2.date():
logger.fdebug('[CONV] pubdate: %s < storedate: %s' % (dateconv2.date(), issconv2.date()))
logger.fdebug('%s is before store date of %s. Ignoring search result as this is not the right issue.' % (pubdate, stdate))
continue
else:
logger.fdebug('[CONV] %s is after store date of %s' % (pubdate, stdate))
except:
#if the above fails, drop down to the integer compare method as a failsafe.
if digitaldate != '0000-00-00' and postdate_int >= digitaldate_int:
logger.fdebug('%s is after DIGITAL store date of %s' % (pubdate, digitaldate))
elif postdate_int < issuedate_int:
logger.fdebug('[INT]pubdate: %s < storedate: %s' % (postdate_int, issuedate_int))
logger.fdebug('%s is before store date of %s. Ignoring search result as this is not the right issue.' % (pubdate, stdate))
continue
else:
logger.fdebug('[INT] %s is after store date of %s' % (pubdate, stdate))
# -- end size constaints.
if '(digital first)' in ComicTitle.lower(): #entry['title'].lower():
dig_moving = re.sub('\(digital first\)', '', ComicTitle.lower()).strip() #entry['title'].lower()).strip()
dig_moving = re.sub('[\s+]', ' ', dig_moving)
dig_mov_end = '%s (Digital First)' % dig_moving
thisentry = dig_mov_end
else:
thisentry = ComicTitle #entry['title']
logger.fdebug('Entry: %s' % thisentry)
cleantitle = thisentry
if 'mixed format' in cleantitle.lower():
cleantitle = re.sub('mixed format', '', cleantitle).strip()
logger.fdebug('removed extra information after issue # that is not necessary: %s' % cleantitle)
# if it's coming from 32P, remove the ' -' at the end as it screws it up.
if nzbprov == '32P':
if cleantitle.endswith(' - '):
cleantitle = cleantitle[:-3]
logger.fdebug('Cleaned up title to : %s' % cleantitle)
#send it to the parser here.
p_comic = filechecker.FileChecker(file=ComicTitle, watchcomic=ComicName)
parsed_comic = p_comic.listFiles()
logger.fdebug('parsed_info: %s' % parsed_comic)
if parsed_comic['parse_status'] == 'success' and (all([booktype is None, parsed_comic['booktype'] == 'issue']) or all([booktype == 'Print', parsed_comic['booktype'] == 'issue']) or all([booktype == 'One-Shot', parsed_comic['booktype'] == 'issue']) or booktype == parsed_comic['booktype']):
try:
fcomic = filechecker.FileChecker(watchcomic=ComicName)
filecomic = fcomic.matchIT(parsed_comic)
except Exception as e:
logger.error('[PARSE-ERROR]: %s' % e)
continue
else:
logger.fdebug('match_check: %s' % filecomic)
if filecomic['process_status'] == 'fail':
logger.fdebug('%s was not a match to %s (%s)' % (cleantitle, ComicName, SeriesYear))
continue
elif booktype != parsed_comic['booktype']:
logger.fdebug('Booktypes do not match. Looking for %s, this is a %s. Ignoring this result.' % (booktype, parsed_comic['booktype']))
continue
else:
logger.fdebug('Unable to parse name properly: %s. Ignoring this result' % filecomic)
continue
#adjust for covers only by removing them entirely...
vers4year = "no"
vers4vol = "no"
versionfound = "no"
if ComicVersion:
ComVersChk = re.sub("[^0-9]", "", ComicVersion)
if ComVersChk == '' or ComVersChk == '1':
ComVersChk = 0
else:
ComVersChk = 0
origvol = None
volfound = False
vol_nono = []
fndcomicversion = None
if parsed_comic['series_volume'] is not None:
versionfound = "yes"
if len(parsed_comic['series_volume'][1:]) == 4 and parsed_comic['series_volume'][1:].isdigit(): #v2013
logger.fdebug("[Vxxxx] Version detected as %s" % (parsed_comic['series_volume']))
vers4year = "yes" #re.sub("[^0-9]", " ", str(ct)) #remove the v
fndcomicversion = parsed_comic['series_volume']
elif len(parsed_comic['series_volume'][1:]) == 1 and parsed_comic['series_volume'][1:].isdigit(): #v2
logger.fdebug("[Vx] Version detected as %s" % parsed_comic['series_volume'])
vers4vol = parsed_comic['series_volume']
fndcomicversion = parsed_comic['series_volume']
elif parsed_comic['series_volume'][1:].isdigit() and len(parsed_comic['series_volume']) < 4:
logger.fdebug('[Vxxx] Version detected as %s' % parsed_comic['series_volume'])
vers4vol = parsed_comic['series_volume']
fndcomicversion = parsed_comic['series_volume']
elif parsed_comic['series_volume'].isdigit() and len(parsed_comic['series_volume']) <=4:
# this stuff is necessary for 32P volume manipulation
if len(parsed_comic['series_volume']) == 4:
vers4year = "yes"
fndcomicversion = parsed_comic['series_volume']
elif len(parsed_comic['series_volume']) == 1:
vers4vol = parsed_comic['series_volume']
fndcomicversion = parsed_comic['series_volume']
elif len(parsed_comic['series_volume']) < 4:
vers4vol = parsed_comic['series_volume']
fndcomicversion = parsed_comic['series_volume']
else:
logger.fdebug("error - unknown length for : %s" % parsed_comic['series_volume'])
yearmatch = "false"
if vers4vol != "no" or vers4year != "no":
logger.fdebug("Series Year not provided but Series Volume detected of %s. Bypassing Year Match." % fndcomicversion)
yearmatch = "true"
elif ComVersChk == 0 and parsed_comic['issue_year'] is None:
logger.fdebug("Series version detected as V1 (only series in existance with that title). Bypassing Year/Volume check")
yearmatch = "true"
elif any([UseFuzzy == "0", UseFuzzy == "2", UseFuzzy is None, IssDateFix != "no"]) and parsed_comic['issue_year'] is not None:
if parsed_comic['issue_year'][:-2] == '19' or parsed_comic['issue_year'][:-2] == '20':
logger.fdebug('year detected: %s' % parsed_comic['issue_year'])
result_comyear = parsed_comic['issue_year']
logger.fdebug('year looking for: %s' % comyear)
if str(comyear) in result_comyear:
logger.fdebug('%s - right years match baby!' % comyear)
yearmatch = "true"
else:
logger.fdebug('%s - not right - years do not match' % comyear)
yearmatch = "false"
if UseFuzzy == "2":
#Fuzzy the year +1 and -1
ComUp = int(ComicYear) + 1
ComDwn = int(ComicYear) - 1
if str(ComUp) in result_comyear or str(ComDwn) in result_comyear:
logger.fdebug('Fuzzy Logic\'d the Year and got a match with a year of %s' % result_comyear)
yearmatch = "true"
else:
logger.fdebug('%s Fuzzy logic\'d the Year and year still did not match.' % comyear)
#let's do this here and save a few extra loops ;)
#fix for issue dates between Nov-Dec/Jan
if IssDateFix != "no" and UseFuzzy is not "2":
if IssDateFix == "01" or IssDateFix == "02" or IssDateFix == "03":
ComicYearFix = int(ComicYear) - 1
if str(ComicYearFix) in result_comyear:
logger.fdebug('Further analysis reveals this was published inbetween Nov-Jan, decreasing year to %s has resulted in a match!' % ComicYearFix)
yearmatch = "true"
else:
logger.fdebug('%s- not the right year.' % comyear)
else:
ComicYearFix = int(ComicYear) + 1
if str(ComicYearFix) in result_comyear:
logger.fdebug('Further analysis reveals this was published inbetween Nov-Jan, incrementing year to %s has resulted in a match!' % ComicYearFix)
yearmatch = "true"
else:
logger.fdebug('%s - not the right year.' % comyear)
elif UseFuzzy == "1": yearmatch = "true"
if yearmatch == "false": continue
annualize = "false"
if 'annual' in ComicName.lower():
logger.fdebug("IssueID of : %s This is an annual...let's adjust." % IssueID)
annualize = "true"
if versionfound == "yes":
logger.fdebug("volume detection commencing - adjusting length.")
logger.fdebug("watch comicversion is %s" % ComicVersion)
logger.fdebug("version found: %s" % fndcomicversion)
logger.fdebug("vers4year: %s" % vers4year)
logger.fdebug("vers4vol: %s" % vers4vol)
if vers4year is not "no" or vers4vol is not "no":
#if the volume is None, assume it's a V1 to increase % hits
if ComVersChk == 0:
D_ComicVersion = 1
else:
D_ComicVersion = ComVersChk
#if this is a one-off, SeriesYear will be None and cause errors.
if SeriesYear is None:
S_ComicVersion = 0
else:
S_ComicVersion = str(SeriesYear)
F_ComicVersion = re.sub("[^0-9]", "", fndcomicversion)
#if the found volume is a vol.0, up it to vol.1 (since there is no V0)
if F_ComicVersion == '0':
#need to convert dates to just be yyyy-mm-dd and do comparison, time operator in the below calc as well which probably throws off$
F_ComicVersion = '1'
if postdate_int is not None:
if digitaldate != '0000-00-00' and all([postdate_int >= digitaldate_int, nzbprov == '32P']):
logger.fdebug('32P torrent discovery. Posting date (%s) is after DIGITAL store date (%s), forcing volume label to be the same as series label (0-Day Enforcement): v%s --> v%s' % (pubdate, digitaldate, F_ComicVersion, S_ComicVersion))
F_ComicVersion = D_ComicVersion
elif all([postdate_int >= issuedate_int, nzbprov == '32P']):
logger.fdebug('32P torrent discovery. Posting date (%s) is after store date (%s), forcing volume label to be the same as series label (0-Day Enforcement): v%s --> v%s' % (pubdate, stdate, F_ComicVersion, S_ComicVersion))
F_ComicVersion = D_ComicVersion
else:
pass
logger.fdebug("FCVersion: %s" % F_ComicVersion)
logger.fdebug("DCVersion: %s" % D_ComicVersion)
logger.fdebug("SCVersion: %s" % S_ComicVersion)
#here's the catch, sometimes annuals get posted as the Pub Year
# instead of the Series they belong to (V2012 vs V2013)
if annualize == "true" and int(ComicYear) == int(F_ComicVersion):
logger.fdebug("We matched on versions for annuals %s" % fndcomicversion)
elif int(F_ComicVersion) == int(D_ComicVersion) or int(F_ComicVersion) == int(S_ComicVersion):
logger.fdebug("We matched on versions...%s" %fndcomicversion)
else:
logger.fdebug("Versions wrong. Ignoring possible match.")
continue
downloadit = False
#-------------------------------------fix this!
try:
pack_test = entry['pack']
except Exception as e:
pack_test = False
if nzbprov == 'Public Torrents' and any([entry['site'] == 'WWT', entry['site'] == 'DEM']):
if entry['site'] == 'WWT':
nzbprov = 'WWT'
else:
nzbprov = 'DEM'
if all([nzbprov == '32P', allow_packs == True, RSS == 'no']):
logger.fdebug('pack: %s' % entry['pack'])
if (all([nzbprov == '32P', RSS == 'no', allow_packs == True]) and any([entry['pack'] == '1', entry['pack'] == '2'])) or (all([nzbprov == 'ddl', pack_test is True])): #allow_packs is True
if nzbprov == '32P':
if entry['pack'] == '2':
logger.fdebug('[PACK-QUEUE] Diamond FreeLeech Pack detected.')
elif entry['pack'] == '1':
logger.fdebug('[PACK-QUEUE] Normal Pack detected. Checking available inkdrops prior to downloading.')
else:
logger.fdebug('[PACK-QUEUE] Invalid Pack.')
else:
logger.fdebug('[PACK-QUEUE] DDL Pack detected for %s.' % entry['filename'])
#find the pack range.
pack_issuelist = None
issueid_info = None
if not entry['title'].startswith('0-Day Comics Pack'):
pack_issuelist = entry['issues']
issueid_info = helpers.issue_find_ids(ComicName, ComicID, pack_issuelist, IssueNumber)
if issueid_info['valid'] == True:
logger.info('Issue Number %s exists within pack. Continuing.' % IssueNumber)
else:
logger.fdebug('Issue Number %s does NOT exist within this pack. Skipping' % IssueNumber)
continue
#pack support.
nowrite = False
if all([nzbprov == 'ddl', 'getcomics' in entry['link']]):
nzbid = entry['id']
else:
nzbid = generate_id(nzbprov, entry['link'])
if manual is not True:
downloadit = True
else:
for x in mylar.COMICINFO:
if all([x['link'] == entry['link'], x['tmpprov'] == tmpprov]) or all([x['nzbid'] == nzbid, x['newznab'] == newznab_host]) or all([x['nzbid'] == nzbid, x['torznab'] == torznab_host]):
nowrite = True
break
if nowrite is False:
if any([nzbprov == 'dognzb', nzbprov == 'nzb.su', nzbprov == 'experimental', 'newznab' in nzbprov]):
tprov = nzbprov
kind = 'usenet'
if newznab_host is not None:
tprov = newznab_host[0]
else:
tprov = nzbprov
kind = 'torrent'
if torznab_host is not None:
tprov = torznab_host[0]
mylar.COMICINFO.append({"ComicName": ComicName,
"ComicID": ComicID,
"IssueID": IssueID,
"ComicVolume": ComicVersion,
"IssueNumber": IssueNumber,
"IssueDate": IssueDate,
"comyear": comyear,
"pack": True,
"pack_numbers": pack_issuelist,
"pack_issuelist": issueid_info,
"modcomicname": entry['title'],
"oneoff": oneoff,
"nzbprov": nzbprov,
"nzbtitle": entry['title'],
"nzbid": nzbid,
"provider": tprov,
"link": entry['link'],
"size": comsize_m,
"tmpprov": tmpprov,
"kind": kind,
"SARC": SARC,
"IssueArcID": IssueArcID,
"newznab": newznab_host,
"torznab": torznab_host})
else:
if filecomic['process_status'] == 'match':
if cmloopit != 4:
logger.fdebug("issue we are looking for is : %s" % findcomiciss)
logger.fdebug("integer value of issue we are looking for : %s" % intIss)
else:
if intIss is None and all([booktype == 'One-Shot', helpers.issuedigits(parsed_comic['issue_number']) == 1000]):
intIss = 1000
else:
intIss = 9999999999
if filecomic['justthedigits'] is not None:
logger.fdebug("issue we found for is : %s" % filecomic['justthedigits'])
comintIss = helpers.issuedigits(filecomic['justthedigits'])
logger.fdebug("integer value of issue we have found : %s" % comintIss)
else:
comintIss = 11111111111
#do this so that we don't touch the actual value but just use it for comparisons
if filecomic['justthedigits'] is None:
pc_in = None
else:
pc_in = helpers.issuedigits(filecomic['justthedigits'])
#issue comparison now as well
if int(intIss) == int(comintIss) or all([cmloopit == 4, findcomiciss is None, pc_in is None]) or all([cmloopit == 4, findcomiciss is None, pc_in == 1]):
nowrite = False
if all([nzbprov == 'torznab', 'worldwidetorrents' in entry['link']]):
nzbid = generate_id(nzbprov, entry['id'])
elif all([nzbprov == 'ddl', 'getcomics' in entry['link']]) or all([nzbprov == 'ddl', RSS == 'yes']):
if RSS == "yes":
entry['id'] = entry['link']
entry['link'] = 'https://getcomics.info/?p='+str(entry['id'])
entry['filename'] = entry['title']
if '/cat/' in entry['link']:
entry['link'] = 'https://getcomics.info/?p='+str(entry['id'])
nzbid = entry['id']
entry['title'] = entry['filename']
else:
nzbid = generate_id(nzbprov, entry['link'])
if manual is not True:
downloadit = True
else:
for x in mylar.COMICINFO:
if all([x['link'] == entry['link'], x['tmpprov'] == tmpprov]) or all([x['nzbid'] == nzbid, x['newznab'] == newznab_host]) or all([x['nzbid'] == nzbid, x['torznab'] == torznab_host]):
nowrite = True
break
#modify the name for annualization to be displayed properly
if annualize == True:
modcomicname = '%s Annual' % ComicName
else:
modcomicname = ComicName
#comicinfo = []
if IssueID is None:
cyear = ComicYear
else:
cyear = comyear
if nowrite is False:
if any([nzbprov == 'dognzb', nzbprov == 'nzb.su', nzbprov == 'experimental', 'newznab' in nzbprov]):
tprov = nzbprov
kind = 'usenet'
if newznab_host is not None:
tprov = newznab_host[0]
else:
kind = 'torrent'
tprov = nzbprov
if torznab_host is not None:
tprov = torznab_host[0]
mylar.COMICINFO.append({"ComicName": ComicName,
"ComicID": ComicID,
"IssueID": IssueID,
"ComicVolume": ComicVersion,
"IssueNumber": IssueNumber,
"IssueDate": IssueDate,
"comyear": cyear,
"pack": False,
"pack_numbers": None,
"pack_issuelist": None,
"modcomicname": modcomicname,
"oneoff": oneoff,
"nzbprov": nzbprov,
"provider": tprov,
"nzbtitle": entry['title'],
"nzbid": nzbid,
"link": entry['link'],
"size": comsize_m,
"tmpprov": tmpprov,
"kind": kind,
"SARC": SARC,
"IssueArcID": IssueArcID,
"newznab": newznab_host,
"torznab": torznab_host})
else:
log2file = log2file + "issues don't match.." + "\n"
downloadit = False
foundc['status'] = False
#logger.fdebug('mylar.COMICINFO: %s' % mylar.COMICINFO)
if downloadit:
try:
if entry['chkit']:
helpers.checkthe_id(ComicID, entry['chkit'])
except:
pass
#generate nzbname
nzbname = nzbname_create(nzbprov, info=mylar.COMICINFO, title=ComicTitle) #entry['title'])
if nzbname is None:
logger.error('[NZBPROVIDER = NONE] Encountered an error using given provider with requested information: %s. You have a blank entry most likely in your newznabs, fix it & restart Mylar' % mylar.COMICINFO)
continue
#generate the send-to and actually send the nzb / torrent.
#logger.info('entry: %s' % entry)
try:
links = {'id': entry['id'],
'link': entry['link']}
except:
links = entry['link']
searchresult = searcher(nzbprov, nzbname, mylar.COMICINFO, links, IssueID, ComicID, tmpprov, newznab=newznab_host, torznab=torznab_host, rss=RSS)
if any([searchresult == 'downloadchk-fail', searchresult == 'double-pp']):
foundc['status'] = False
continue
elif any([searchresult == 'torrent-fail', searchresult == 'nzbget-fail', searchresult == 'sab-fail', searchresult == 'blackhole-fail', searchresult == 'ddl-fail']):
foundc['status'] = False
return foundc
#nzbid, nzbname, sent_to
nzbid = searchresult['nzbid']
nzbname = searchresult['nzbname']
sent_to = searchresult['sent_to']
alt_nzbname = searchresult['alt_nzbname']
t_hash = searchresult['t_hash']
if searchresult['SARC'] is not None:
SARC = searchresult['SARC']
foundc['info'] = searchresult
foundc['status'] = True
done = True
break
if done == True:
#cmloopit == 1 #let's make sure it STOPS searching after a sucessful match.
break
#cmloopit-=1
#if cmloopit < 1 and c_alpha is not None and seperatealpha == "no" and foundc['status'] is False:
# logger.info("Alphanumerics detected within IssueNumber. Seperating from Issue # and re-trying.")
# cmloopit = origcmloopit
# seperatealpha = "yes"
findloop+=1
if foundc['status'] is True:
if 'Public Torrents' in tmpprov and any([nzbprov == 'WWT', nzbprov == 'DEM']):
tmpprov = re.sub('Public Torrents', nzbprov, tmpprov)
foundcomic.append("yes")
logger.info('mylar.COMICINFO: %s' % mylar.COMICINFO)
if mylar.COMICINFO[0]['pack'] is True:
try:
issinfo = mylar.COMICINFO[0]['pack_issuelist']
except:
issinfo = mylar.COMICINFO['pack_issuelist']
if issinfo is not None:
#we need to get EVERY issue ID within the pack and update the log to reflect that they're being downloaded via a pack.
try:
logger.fdebug('Found matching comic within pack...preparing to send to Updater with IssueIDs: %s and nzbname of %s' % (issueid_info, nzbname))
except NameError:
logger.fdebug('Did not find issueid_info')
#because packs need to have every issue that's not already Downloaded in a Snatched status, throw it to the updater here as well.
for isid in issinfo['issues']:
updater.nzblog(isid['issueid'], nzbname, ComicName, SARC=SARC, IssueArcID=IssueArcID, id=nzbid, prov=tmpprov, oneoff=oneoff)
updater.foundsearch(ComicID, isid['issueid'], mode='series', provider=tmpprov)
notify_snatch(sent_to, mylar.COMICINFO[0]['ComicName'], mylar.COMICINFO[0]['comyear'], mylar.COMICINFO[0]['pack_numbers'], nzbprov, True)
else:
notify_snatch(sent_to, mylar.COMICINFO[0]['ComicName'], mylar.COMICINFO[0]['comyear'], None, nzbprov, True)
else:
if alt_nzbname is None or alt_nzbname == '':
logger.fdebug('Found matching comic...preparing to send to Updater with IssueID: %s and nzbname: %s' % (IssueID, nzbname))
if '[RSS]' in tmpprov: tmpprov = re.sub('\[RSS\]', '', tmpprov).strip()
updater.nzblog(IssueID, nzbname, ComicName, SARC=SARC, IssueArcID=IssueArcID, id=nzbid, prov=tmpprov, oneoff=oneoff)
else:
logger.fdebug('Found matching comic...preparing to send to Updater with IssueID: %s and nzbname: %s [%s]' % (IssueID, nzbname, alt_nzbname))
if '[RSS]' in tmpprov: tmpprov = re.sub('\[RSS\]', '', tmpprov).strip()
updater.nzblog(IssueID, nzbname, ComicName, SARC=SARC, IssueArcID=IssueArcID, id=nzbid, prov=tmpprov, alt_nzbname=alt_nzbname, oneoff=oneoff)
#send out the notifications for the snatch.
if any([oneoff is True, IssueID is None]):
cyear = ComicYear
else:
cyear = comyear
notify_snatch(sent_to, ComicName, cyear, IssueNumber, nzbprov, False)
prov_count == 0
mylar.TMP_PROV = nzbprov
#if mylar.SAB_PARAMS is not None:
# #should be threaded....
# ss = sabnzbd.SABnzbd(mylar.SAB_PARAMS)
# sendtosab = ss.sender()
# if all([sendtosab['status'] is True, mylar.CONFIG.SAB_CLIENT_POST_PROCESSING is True]):
# mylar.NZB_QUEUE.put(sendtosab)
return foundc
else:
#logger.fdebug('prov_count: ' + str(prov_count))
foundcomic.append("no")
#if IssDateFix == "no":
#logger.info('Could not find Issue ' + str(IssueNumber) + ' of ' + ComicName + '(' + str(comyear) + ') using ' + str(tmpprov) + '. Status kept as wanted.' )
#break
return foundc
def searchforissue(issueid=None, new=False, rsscheck=None, manual=False):
if rsscheck == 'yes':
while mylar.SEARCHLOCK is True:
time.sleep(5)
if mylar.SEARCHLOCK is True:
logger.info('A search is currently in progress....queueing this up again to try in a bit.')
return {'status': 'IN PROGRESS'}
myDB = db.DBConnection()
ens = [x for x in mylar.CONFIG.EXTRA_NEWZNABS if x[5] == '1']
ets = [x for x in mylar.CONFIG.EXTRA_TORZNABS if x[4] == '1']
if (any([mylar.CONFIG.ENABLE_DDL is True, mylar.CONFIG.NZBSU is True, mylar.CONFIG.DOGNZB is True, mylar.CONFIG.EXPERIMENTAL is True]) or all([mylar.CONFIG.NEWZNAB is True, len(ens) > 0]) and any([mylar.USE_SABNZBD is True, mylar.USE_NZBGET is True, mylar.USE_BLACKHOLE is True])) or (all([mylar.CONFIG.ENABLE_TORRENT_SEARCH is True, mylar.CONFIG.ENABLE_TORRENTS is True]) and (any([mylar.CONFIG.ENABLE_PUBLIC is True, mylar.CONFIG.ENABLE_32P is True]) or all([mylar.CONFIG.ENABLE_TORZNAB is True, len(ets) > 0]))):
if not issueid or rsscheck:
if rsscheck:
logger.info('Initiating RSS Search Scan at the scheduled interval of %s minutes' % mylar.CONFIG.RSS_CHECKINTERVAL)
mylar.SEARCHLOCK = True
else:
logger.info('Initiating check to add Wanted items to Search Queue....')
myDB = db.DBConnection()
stloop = 2 # 2 levels - one for issues, one for storyarcs - additional for annuals below if enabled
results = []
if mylar.CONFIG.ANNUALS_ON:
stloop+=1
while (stloop > 0):
if stloop == 1:
if mylar.CONFIG.FAILED_DOWNLOAD_HANDLING and mylar.CONFIG.FAILED_AUTO:
issues_1 = myDB.select('SELECT * from issues WHERE Status="Wanted" OR Status="Failed"')
else:
issues_1 = myDB.select('SELECT * from issues WHERE Status="Wanted"')
for iss in issues_1:
results.append({'ComicID': iss['ComicID'],
'IssueID': iss['IssueID'],
'Issue_Number': iss['Issue_Number'],
'IssueDate': iss['IssueDate'],
'StoreDate': iss['ReleaseDate'],
'DigitalDate': iss['DigitalDate'],
'SARC': None,
'StoryArcID': None,
'IssueArcID': None,
'mode': 'want',
'DateAdded': iss['DateAdded']
})
elif stloop == 2:
if mylar.CONFIG.SEARCH_STORYARCS is True or rsscheck:
if mylar.CONFIG.FAILED_DOWNLOAD_HANDLING and mylar.CONFIG.FAILED_AUTO:
issues_2 = myDB.select('SELECT * from storyarcs WHERE Status="Wanted" OR Status="Failed"')
else:
issues_2 = myDB.select('SELECT * from storyarcs WHERE Status="Wanted"')
cnt=0
for iss in issues_2:
results.append({'ComicID': iss['ComicID'],
'IssueID': iss['IssueID'],
'Issue_Number': iss['IssueNumber'],
'IssueDate': iss['IssueDate'],
'StoreDate': iss['ReleaseDate'],
'DigitalDate': iss['DigitalDate'],
'SARC': iss['StoryArc'],
'StoryArcID': iss['StoryArcID'],
'IssueArcID': iss['IssueArcID'],
'mode': 'story_arc',
'DateAdded': iss['DateAdded']
})
cnt+=1
logger.info('Storyarcs to be searched for : %s' % cnt)
elif stloop == 3:
if mylar.CONFIG.FAILED_DOWNLOAD_HANDLING and mylar.CONFIG.FAILED_AUTO:
issues_3 = myDB.select('SELECT * from annuals WHERE Status="Wanted" OR Status="Failed"')
else:
issues_3 = myDB.select('SELECT * from annuals WHERE Status="Wanted"')
for iss in issues_3:
results.append({'ComicID': iss['ComicID'],
'IssueID': iss['IssueID'],
'Issue_Number': iss['Issue_Number'],
'IssueDate': iss['IssueDate'],
'StoreDate': iss['ReleaseDate'], #need to replace with Store date
'DigitalDate': iss['DigitalDate'],
'SARC': None,
'StoryArcID': None,
'IssueArcID': None,
'mode': 'want_ann',
'DateAdded': iss['DateAdded']
})
stloop-=1
new = True
#to-do: re-order the results list so it's most recent to least recent.
for result in sorted(results, key=itemgetter('StoreDate'), reverse=True):
#status issue check - check status to see if it's Downloaded / Snatched already due to concurrent searches possible.
if result['IssueID'] is not None:
if result['mode'] == 'story_arc':
isscheck = helpers.issue_status(result['IssueArcID'])
else:
isscheck = helpers.issue_status(result['IssueID'])
#isscheck will return True if already Downloaded / Snatched, False if it's still in a Wanted status.
if isscheck is True:
logger.fdebug('Issue is already in a Downloaded / Snatched status.')
continue
OneOff = False
storyarc_watchlist = False
comic = myDB.selectone("SELECT * from comics WHERE ComicID=? AND ComicName != 'None'", [result['ComicID']]).fetchone()
if all([comic is None, result['mode'] == 'story_arc']):
comic = myDB.selectone("SELECT * from storyarcs WHERE StoryArcID=? AND IssueArcID=?", [result['StoryArcID'],result['IssueArcID']]).fetchone()
if comic is None:
logger.fdebug('%s has no associated comic information in the Arc. Skipping searching for this series.' % result['ComicID'])
continue
else:
OneOff = True
elif comic is None:
logger.fdebug('%s has no associated comic information in the Arc. Skipping searching for this series.' % result['ComicID'])
continue
else:
storyarc_watchlist = True
if result['StoreDate'] == '0000-00-00' or result['StoreDate'] is None:
if any([result['IssueDate'] is None, result['IssueDate'] == '0000-00-00']) and result['DigitalDate'] == '0000-00-00':
logger.fdebug('ComicID: %s has invalid Date data. Skipping searching for this series.' % result['ComicID'])
continue
foundNZB = "none"
AllowPacks = False
if all([result['mode'] == 'story_arc', storyarc_watchlist is False]):
Comicname_filesafe = helpers.filesafe(comic['ComicName'])
SeriesYear = comic['SeriesYear']
Publisher = comic['Publisher']
AlternateSearch = None
UseFuzzy = None
ComicVersion = comic['Volume']
TorrentID_32p = None
booktype = comic['Type']
else:
Comicname_filesafe = comic['ComicName_Filesafe']
SeriesYear = comic['ComicYear']
Publisher = comic['ComicPublisher']
AlternateSearch = comic['AlternateSearch']
UseFuzzy = comic['UseFuzzy']
ComicVersion = comic['ComicVersion']
TorrentID_32p = comic['TorrentID_32P']
booktype = comic['Type']
if any([comic['AllowPacks'] == 1, comic['AllowPacks'] == '1']):
AllowPacks = True
IssueDate = result['IssueDate']
StoreDate = result['StoreDate']
DigitalDate = result['DigitalDate']
if result['IssueDate'] is None:
ComicYear = SeriesYear
else:
ComicYear = str(result['IssueDate'])[:4]
if result['DateAdded'] is None:
DA = datetime.datetime.today()
DateAdded = DA.strftime('%Y-%m-%d')
if result['mode'] == 'want':
table = 'issues'
elif result['mode'] == 'want_ann':
table = 'annuals'
elif result['mode'] == 'story_arc':
table = 'storyarcs'
logger.fdebug('%s #%s did not have a DateAdded recorded, setting it : %s' % (comic['ComicName'], result['Issue_Number'], DateAdded))
myDB.upsert(table, {'DateAdded': DateAdded}, {'IssueID': result['IssueID']})
else:
DateAdded = result['DateAdded']
if rsscheck is None and DateAdded >= mylar.SEARCH_TIER_DATE:
logger.info('adding: ComicID:%s IssueiD: %s' % (result['ComicID'], result['IssueID']))
mylar.SEARCH_QUEUE.put({'comicname': comic['ComicName'], 'seriesyear': SeriesYear, 'issuenumber': result['Issue_Number'], 'issueid': result['IssueID'], 'comicid': result['ComicID'], 'booktype': booktype})
continue
mode = result['mode']
foundNZB, prov = search_init(comic['ComicName'], result['Issue_Number'], str(ComicYear), SeriesYear, Publisher, IssueDate, StoreDate, result['IssueID'], AlternateSearch, UseFuzzy, ComicVersion, SARC=result['SARC'], IssueArcID=result['IssueArcID'], mode=mode, rsscheck=rsscheck, ComicID=result['ComicID'], filesafe=Comicname_filesafe, allow_packs=AllowPacks, oneoff=OneOff, torrentid_32p=TorrentID_32p, digitaldate=DigitalDate, booktype=booktype)
if foundNZB['status'] is True:
updater.foundsearch(result['ComicID'], result['IssueID'], mode=mode, provider=prov, SARC=result['SARC'], IssueArcID=result['IssueArcID'], hash=foundNZB['info']['t_hash'])
if rsscheck:
logger.info('Completed RSS Search scan')
if mylar.SEARCHLOCK is True:
mylar.SEARCHLOCK = False
else:
logger.info('Completed Queueing API Search scan')
if mylar.SEARCHLOCK is True:
mylar.SEARCHLOCK = False
else:
mylar.SEARCHLOCK = True
result = myDB.selectone('SELECT * FROM issues where IssueID=?', [issueid]).fetchone()
mode = 'want'
oneoff = False
if result is None:
result = myDB.selectone('SELECT * FROM annuals where IssueID=?', [issueid]).fetchone()
mode = 'want_ann'
if result is None:
result = myDB.selectone('SELECT * FROM storyarcs where IssueArcID=?', [issueid]).fetchone()
mode = 'story_arc'
oneoff = True
if result is None:
result = myDB.selectone('SELECT * FROM weekly where IssueID=?', [issueid]).fetchone()
mode = 'pullwant'
oneoff = True
if result is None:
logger.fdebug("Unable to locate IssueID - you probably should delete/refresh the series.")
mylar.SEARCHLOCK = False
return
allow_packs = False
ComicID = result['ComicID']
if mode == 'story_arc':
ComicName = result['ComicName']
Comicname_filesafe = helpers.filesafe(ComicName)
SeriesYear = result['SeriesYear']
IssueNumber = result['IssueNumber']
Publisher = result['Publisher']
AlternateSearch = None
UseFuzzy = None
ComicVersion = result['Volume']
SARC = result['StoryArc']
IssueArcID = issueid
actissueid = None
IssueDate = result['IssueDate']
StoreDate = result['ReleaseDate']
DigitalDate = result['DigitalDate']
TorrentID_32p = None
booktype = result['Type']
elif mode == 'pullwant':
ComicName = result['COMIC']
Comicname_filesafe = helpers.filesafe(ComicName)
SeriesYear = result['seriesyear']
IssueNumber = result['ISSUE']
Publisher = result['PUBLISHER']
AlternateSearch = None
UseFuzzy = None
ComicVersion = result['volume']
SARC = None
IssueArcID = None
actissueid = issueid
TorrentID_32p = None
IssueDate = result['SHIPDATE']
StoreDate = IssueDate
DigitalDate = '0000-00-00'
booktype = result['format']
else:
comic = myDB.selectone('SELECT * FROM comics where ComicID=?', [ComicID]).fetchone()
if mode == 'want_ann':
ComicName = result['ComicName']
Comicname_filesafe = None
AlternateSearch = None
else:
ComicName = comic['ComicName']
Comicname_filesafe = comic['ComicName_Filesafe']
AlternateSearch = comic['AlternateSearch']
SeriesYear = comic['ComicYear']
IssueNumber = result['Issue_Number']
Publisher = comic['ComicPublisher']
UseFuzzy = comic['UseFuzzy']
ComicVersion = comic['ComicVersion']
IssueDate = result['IssueDate']
StoreDate = result['ReleaseDate']
DigitalDate = result['DigitalDate']
SARC = None
IssueArcID = None
actissueid = issueid
TorrentID_32p = comic['TorrentID_32P']
booktype = comic['Type']
if any([comic['AllowPacks'] == 1, comic['AllowPacks'] == '1']):
allow_packs = True
if IssueDate is None:
IssueYear = SeriesYear
else:
IssueYear = str(IssueDate)[:4]
foundNZB, prov = search_init(ComicName, IssueNumber, str(IssueYear), SeriesYear, Publisher, IssueDate, StoreDate, actissueid, AlternateSearch, UseFuzzy, ComicVersion, SARC=SARC, IssueArcID=IssueArcID, mode=mode, rsscheck=rsscheck, ComicID=ComicID, filesafe=Comicname_filesafe, allow_packs=allow_packs, oneoff=oneoff, manual=manual, torrentid_32p=TorrentID_32p, digitaldate=DigitalDate, booktype=booktype)
if manual is True:
mylar.SEARCHLOCK = False
return foundNZB
if foundNZB['status'] is True:
logger.fdebug('I found %s #%s' % (ComicName, IssueNumber))
updater.foundsearch(ComicID, actissueid, mode=mode, provider=prov, SARC=SARC, IssueArcID=IssueArcID, hash=foundNZB['info']['t_hash'])
if mylar.SEARCHLOCK is True:
mylar.SEARCHLOCK = False
return foundNZB
else:
if rsscheck:
logger.warn('There are no search providers enabled atm - not performing an RSS check for obvious reasons')
else:
logger.warn('There are no search providers enabled atm - not performing an Force Check for obvious reasons')
return
def searchIssueIDList(issuelist):
myDB = db.DBConnection()
ens = [x for x in mylar.CONFIG.EXTRA_NEWZNABS if x[5] == '1']
ets = [x for x in mylar.CONFIG.EXTRA_TORZNABS if x[4] == '1']
if (any([mylar.CONFIG.NZBSU is True, mylar.CONFIG.DOGNZB is True, mylar.CONFIG.EXPERIMENTAL is True]) or all([mylar.CONFIG.NEWZNAB is True, len(ens) > 0]) and any([mylar.USE_SABNZBD is True, mylar.USE_NZBGET is True, mylar.USE_BLACKHOLE is True])) or (all([mylar.CONFIG.ENABLE_TORRENT_SEARCH is True, mylar.CONFIG.ENABLE_TORRENTS is True]) and (any([mylar.CONFIG.ENABLE_PUBLIC is True, mylar.CONFIG.ENABLE_32P is True]) or all([mylar.CONFIG.NEWZNAB is True, len(ets) > 0]))):
for issueid in issuelist:
logger.info('searching for issueid: %s' % issueid)
issue = myDB.selectone('SELECT * from issues WHERE IssueID=?', [issueid]).fetchone()
mode = 'want'
if issue is None:
issue = myDB.selectone('SELECT * from annuals WHERE IssueID=?', [issueid]).fetchone()
mode = 'want_ann'
if issue is None:
logger.warn('Unable to determine IssueID - perhaps you need to delete/refresh series? Skipping this entry: %s' % issueid)
continue
if any([issue['Status'] == 'Downloaded', issue['Status'] == 'Snatched']):
logger.fdebug('Issue is already in a Downloaded / Snatched status.')
continue
comic = myDB.selectone('SELECT * from comics WHERE ComicID=?', [issue['ComicID']]).fetchone()
foundNZB = "none"
SeriesYear = comic['ComicYear']
AlternateSearch = comic['AlternateSearch']
Publisher = comic['ComicPublisher']
UseFuzzy = comic['UseFuzzy']
ComicVersion = comic['ComicVersion']
TorrentID_32p = comic['TorrentID_32P']
booktype = comic['Type']
if issue['IssueDate'] == None:
IssueYear = comic['ComicYear']
else:
IssueYear = str(issue['IssueDate'])[:4]
if any([comic['AllowPacks'] == 1, comic['AllowPacks'] == '1']):
AllowPacks = True
else:
AllowPacks = False
foundNZB, prov = search_init(comic['ComicName'], issue['Issue_Number'], str(IssueYear), comic['ComicYear'], Publisher, issue['IssueDate'], issue['ReleaseDate'], issue['IssueID'], AlternateSearch, UseFuzzy, ComicVersion, SARC=None, IssueArcID=None, mode=mode, ComicID=issue['ComicID'], filesafe=comic['ComicName_Filesafe'], allow_packs=AllowPacks, torrentid_32p=TorrentID_32p, digitaldate=issue['DigitalDate'], booktype=booktype)
if foundNZB['status'] is True:
updater.foundsearch(ComicID=issue['ComicID'], IssueID=issue['IssueID'], mode=mode, provider=prov, hash=foundNZB['info']['t_hash'])
logger.info('Completed search request.')
else:
logger.warn('There are no search providers enabled atm - not performing the requested search for obvious reasons')
def provider_sequence(nzbprovider, torprovider, newznab_hosts, torznab_hosts, ddlprovider):
#provider order sequencing here.
newznab_info = []
torznab_info = []
prov_order = []
nzbproviders_lower = [x.lower() for x in nzbprovider]
torproviders_lower = [y.lower() for y in torprovider]
ddlproviders_lower = [z.lower() for z in ddlprovider]
if len(mylar.CONFIG.PROVIDER_ORDER) > 0:
for pr_order in sorted(mylar.CONFIG.PROVIDER_ORDER.items(), key=itemgetter(0), reverse=False):
if any(pr_order[1].lower() in y for y in torproviders_lower) or any(pr_order[1].lower() in x for x in nzbproviders_lower) or any(pr_order[1].lower() == z for z in ddlproviders_lower):
if any(pr_order[1].lower() in x for x in nzbproviders_lower):
# this is for nzb providers
for np in nzbprovider:
if all(['newznab' in np, pr_order[1].lower() in np.lower()]):
for newznab_host in newznab_hosts:
if newznab_host[0].lower() == pr_order[1].lower():
prov_order.append(np) #newznab_host)
newznab_info.append({"provider": np,
"info": newznab_host})
break
else:
if newznab_host[0] == "":
if newznab_host[1].lower() == pr_order[1].lower():
prov_order.append(np) #newznab_host)
newznab_info.append({"provider": np,
"info": newznab_host})
break
elif pr_order[1].lower() in np.lower():
prov_order.append(pr_order[1])
break
elif any(pr_order[1].lower() in y for y in torproviders_lower):
for tp in torprovider:
if all(['torznab' in tp, pr_order[1].lower() in tp.lower()]):
for torznab_host in torznab_hosts:
if torznab_host[0].lower() == pr_order[1].lower():
prov_order.append(tp)
torznab_info.append({"provider": tp,
"info": torznab_host})
break
else:
if torznab_host[0] == "":
if torznab_host[1].lower() == pr_order[1].lower():
prov_order.append(tp)
torznab_info.append({"provider": tp,
"info": torznab_host})
break
elif (pr_order[1].lower() in tp.lower()):
prov_order.append(pr_order[1])
break
elif any(pr_order[1].lower() == z for z in ddlproviders_lower):
for dd in ddlprovider:
if (dd.lower() == pr_order[1].lower()):
prov_order.append(pr_order[1])
break
return prov_order, torznab_info, newznab_info
def nzbname_create(provider, title=None, info=None):
#the nzbname here is used when post-processing
# it searches nzblog which contains the nzbname to pull out the IssueID and start the post-processing
# it is also used to keep the hashinfo for the nzbname in case it fails downloading, it will get put into the failed db for future exclusions
nzbname = None
if mylar.USE_BLACKHOLE and all([provider != '32P', provider != 'WWT', provider != 'DEM']):
if os.path.exists(mylar.CONFIG.BLACKHOLE_DIR):
#load in the required info to generate the nzb names when required (blackhole only)
ComicName = info[0]['ComicName']
IssueNumber = info[0]['IssueNumber']
comyear = info[0]['comyear']
#pretty this biatch up.
BComicName = re.sub('[\:\,\/\?\']', '', str(ComicName))
Bl_ComicName = re.sub('[\&]', 'and', str(BComicName))
if u'\xbd' in IssueNumber:
str_IssueNumber = '0.5'
elif u'\xbc' in IssueNumber:
str_IssueNumber = '0.25'
elif u'\xbe' in IssueNumber:
str_IssueNumber = '0.75'
elif u'\u221e' in IssueNumber:
str_IssueNumber = 'infinity'
else:
str_IssueNumber = IssueNumber
nzbname = '%s.%s.(%s)' % (re.sub(" ", ".", str(Bl_ComicName)), str_IssueNumber, comyear)
logger.fdebug('nzb name to be used for post-processing is : %s' % nzbname)
elif any([provider == '32P', provider == 'WWT', provider == 'DEM', provider == 'ddl']):
#filesafe the name cause people are idiots when they post sometimes.
nzbname = re.sub('\s{2,}', ' ', helpers.filesafe(title)).strip()
#let's change all space to decimals for simplicity
nzbname = re.sub(" ", ".", nzbname)
#gotta replace & or escape it
nzbname = re.sub("\&", 'and', nzbname)
nzbname = re.sub('[\,\:\?\']', '', nzbname)
if nzbname.lower().endswith('.torrent'):
nzbname = re.sub('.torrent', '', nzbname)
else:
# let's change all space to decimals for simplicity
logger.fdebug('[SEARCHER] entry[title]: %s' % title)
#gotta replace & or escape it
nzbname = re.sub('\&(amp;)?|\&', 'and', title)
nzbname = re.sub('[\,\:\?\'\+]', '', nzbname)
nzbname = re.sub('[\(\)]', ' ', nzbname)
logger.fdebug('[SEARCHER] nzbname (remove chars): %s' % nzbname)
nzbname = re.sub('.cbr', '', nzbname).strip()
nzbname = re.sub('.cbz', '', nzbname).strip()
nzbname = re.sub('[\.\_]', ' ', nzbname).strip()
nzbname = re.sub('\s+', ' ', nzbname) #make sure we remove the extra spaces.
logger.fdebug('[SEARCHER] nzbname (\s): %s' % nzbname)
nzbname = re.sub(' ', '.', nzbname)
#remove the [1/9] parts or whatever kinda crap (usually in experimental results)
pattern = re.compile(r'\W\d{1,3}\/\d{1,3}\W')
match = pattern.search(nzbname)
if match:
nzbname = re.sub(match.group(), '', nzbname).strip()
logger.fdebug('[SEARCHER] end nzbname: %s' % nzbname)
if nzbname is None:
return None
else:
logger.fdebug('nzbname used for post-processing: %s' % nzbname)
return nzbname
def searcher(nzbprov, nzbname, comicinfo, link, IssueID, ComicID, tmpprov, directsend=None, newznab=None, torznab=None, rss=None):
alt_nzbname = None
#load in the details of the issue from the tuple.
ComicName = comicinfo[0]['ComicName']
IssueNumber = comicinfo[0]['IssueNumber']
comyear = comicinfo[0]['comyear']
modcomicname = comicinfo[0]['modcomicname']
oneoff = comicinfo[0]['oneoff']
try:
SARC = comicinfo[0]['SARC']
except:
SARC = None
try:
IssueArcID = comicinfo[0]['IssueArcID']
except:
IssueArcID = None
#setup the priorities.
if mylar.CONFIG.SAB_PRIORITY:
if mylar.CONFIG.SAB_PRIORITY == "Default": sabpriority = "-100"
elif mylar.CONFIG.SAB_PRIORITY == "Low": sabpriority = "-1"
elif mylar.CONFIG.SAB_PRIORITY == "Normal": sabpriority = "0"
elif mylar.CONFIG.SAB_PRIORITY == "High": sabpriority = "1"
elif mylar.CONFIG.SAB_PRIORITY == "Paused": sabpriority = "-2"
else:
#if sab priority isn't selected, default to Normal (0)
sabpriority = "0"
if mylar.CONFIG.NZBGET_PRIORITY:
if mylar.CONFIG.NZBGET_PRIORITY == "Default": nzbgetpriority = "0"
elif mylar.CONFIG.NZBGET_PRIORITY == "Low": nzbgetpriority = "-50"
elif mylar.CONFIG.NZBGET_PRIORITY == "Normal": nzbgetpriority = "0"
elif mylar.CONFIG.NZBGET_PRIORITY == "High": nzbgetpriority = "50"
#there's no priority for "paused", so set "Very Low" and deal with that later...
elif mylar.CONFIG.NZBGET_PRIORITY == "Paused": nzbgetpriority = "-100"
else:
#if sab priority isn't selected, default to Normal (0)
nzbgetpriority = "0"
if nzbprov == 'torznab' or nzbprov == 'ddl':
if nzbprov == 'ddl':
nzbid = link['id']
else:
nzbid = generate_id(nzbprov, link['id'])
link = link['link']
else:
try:
link = link['link']
except:
link = link
nzbid = generate_id(nzbprov, link)
logger.fdebug('issues match!')
if 'Public Torrents' in tmpprov and any([nzbprov == 'WWT', nzbprov == 'DEM']):
tmpprov = re.sub('Public Torrents', nzbprov, tmpprov)
if comicinfo[0]['pack'] == True:
if '0-Day Comics Pack' not in comicinfo[0]['ComicName']:
logger.info('Found %s (%s) issue: %s using %s within a pack containing issues %s' % (ComicName, comyear, IssueNumber, tmpprov, comicinfo[0]['pack_numbers']))
else:
logger.info('Found %s using %s for %s' % (ComicName, tmpprov, comicinfo[0]['IssueDate']))
else:
if any([oneoff is True, IssueID is None]):
#one-off information
logger.fdebug('ComicName: %s' % ComicName)
logger.fdebug('Issue: %s' % IssueNumber)
logger.fdebug('Year: %s' % comyear)
logger.fdebug('IssueDate: %s' % comicinfo[0]['IssueDate'])
if IssueNumber is None:
logger.info('Found %s (%s) using %s' % (ComicName, comyear, tmpprov))
else:
logger.info('Found %s (%s) #%s using %s' % (ComicName, comyear, IssueNumber, tmpprov))
logger.fdebug('link given by: %s' % nzbprov)
if mylar.CONFIG.FAILED_DOWNLOAD_HANDLING:
logger.info('nzbid: %s' % nzbid)
logger.info('IssueID: %s' % IssueID)
logger.info('oneoff: %s' % oneoff)
if all([nzbid is not None, IssueID is not None, oneoff is False]):
# --- this causes any possible snatch to get marked as a Failed download when doing a one-off search...
#try:
# # only nzb providers will have a filen, try it and pass exception
# if IssueID is None:
# logger.fdebug('One-off mode was initiated - Failed Download handling for : ' + ComicName + ' #' + str(IssueNumber))
# comicinfo = {"ComicName": ComicName,
# "IssueNumber": IssueNumber}
# return FailedMark(ComicID=ComicID, IssueID=IssueID, id=nzbid, nzbname=nzbname, prov=nzbprov, oneoffinfo=comicinfo)
#except:
# pass
call_the_fail = Failed.FailedProcessor(nzb_name=nzbname, id=nzbid, issueid=IssueID, comicid=ComicID, prov=tmpprov)
check_the_fail = call_the_fail.failed_check()
if check_the_fail == 'Failed':
logger.fdebug('[FAILED_DOWNLOAD_CHECKER] [%s] Marked as a bad download : %s' % (tmpprov, nzbid))
return "downloadchk-fail"
elif check_the_fail == 'Good':
logger.fdebug('[FAILED_DOWNLOAD_CHECKER] This is not in the failed downloads list. Will continue with the download.')
else:
logger.fdebug('[FAILED_DOWNLOAD_CHECKER] Failed download checking is not available for one-off downloads atm. Fixed soon!')
if link and all([nzbprov != 'WWT', nzbprov != 'DEM', nzbprov != '32P', nzbprov != 'torznab', nzbprov != 'ddl']):
#generate nzbid here.
nzo_info = {}
filen = None
nzbhydra = False
payload = None
headers = {'User-Agent': str(mylar.USER_AGENT)}
#link doesn't have the apikey - add it and use ?t=get for newznab based.
if nzbprov == 'newznab' or nzbprov == 'nzb.su':
#need to basename the link so it just has the id/hash.
#rss doesn't store apikey, have to put it back.
if nzbprov == 'newznab':
name_newznab = newznab[0].rstrip()
host_newznab = newznab[1].rstrip()
if host_newznab[len(host_newznab) -1:len(host_newznab)] != '/':
host_newznab_fix = str(host_newznab) + "/"
else:
host_newznab_fix = host_newznab
#account for nzbmegasearch & nzbhydra
if 'searchresultid' in link:
logger.fdebug('NZBHydra V1 url detected. Adjusting...')
nzbhydra = True
else:
apikey = newznab[3].rstrip()
if rss == 'yes':
uid = newznab[4].rstrip()
payload = {'r': str(apikey)}
if uid is not None:
payload['i'] = uid
verify = bool(newznab[2])
else:
down_url = 'https://api.nzb.su/api'
apikey = mylar.CONFIG.NZBSU_APIKEY
verify = bool(mylar.CONFIG.NZBSU_VERIFY)
if nzbhydra is True:
down_url = link
verify = False
elif 'https://cdn.' in link:
down_url = host_newznab_fix + 'api'
logger.fdebug('Re-routing incorrect RSS URL response for NZBGeek to correct API')
payload = {'t': 'get',
'id': str(nzbid),
'apikey': str(apikey)}
else:
down_url = link
elif nzbprov == 'dognzb':
#dognzb - need to add back in the dog apikey
down_url = urljoin(link, str(mylar.CONFIG.DOGNZB_APIKEY))
verify = bool(mylar.CONFIG.DOGNZB_VERIFY)
else:
#experimental - direct link.
down_url = link
headers = None
verify = False
if payload is None:
tmp_line = down_url
tmp_url = down_url
tmp_url_st = tmp_url.find('apikey=')
if tmp_url_st is -1:
tmp_url_st = tmp_url.find('r=')
tmp_line = tmp_url[:tmp_url_st+2]
else:
tmp_line = tmp_url[:tmp_url_st+7]
tmp_line += 'xYOUDONTNEEDTOKNOWTHISx'
tmp_url_en = tmp_url.find('&', tmp_url_st)
if tmp_url_en is -1:
tmp_url_en = len(tmp_url)
tmp_line += tmp_url[tmp_url_en:]
#tmp_url = helpers.apiremove(down_url.copy(), '&')
logger.fdebug('[PAYLOAD-NONE] Download URL: %s [VerifySSL: %s]' % (tmp_line, verify))
else:
tmppay = payload.copy()
tmppay['apikey'] = 'YOUDONTNEEDTOKNOWTHIS'
logger.fdebug('[PAYLOAD] Download URL: %s?%s [VerifySSL: %s]' % (down_url, urllib.urlencode(tmppay), verify))
if down_url.startswith('https') and verify == False:
try:
from requests.packages.urllib3 import disable_warnings
disable_warnings()
except:
logger.warn('Unable to disable https warnings. Expect some spam if using https nzb providers.')
try:
r = requests.get(down_url, params=payload, verify=verify, headers=headers)
except Exception, e:
logger.warn('Error fetching data from %s: %s' % (tmpprov, e))
return "sab-fail"
logger.fdebug('Status code returned: %s' % r.status_code)
try:
nzo_info['filename'] = r.headers['x-dnzb-name']
filen = r.headers['x-dnzb-name']
except KeyError:
filen = None
try:
nzo_info['propername'] = r.headers['x-dnzb-propername']
except KeyError:
pass
try:
nzo_info['failure'] = r.headers['x-dnzb-failure']
except KeyError:
pass
try:
nzo_info['details'] = r.headers['x-dnzb-details']
except KeyError:
pass
if filen is None:
try:
filen = r.headers['content-disposition'][r.headers['content-disposition'].index("filename=") + 9:].strip(';').strip('"')
logger.fdebug('filename within nzb: %s' % filen)
except:
pass
if filen is None:
if payload is None:
logger.error('[PAYLOAD:NONE] Unable to download nzb from link: %s [%s]' % (down_url, link))
else:
errorlink = down_url + '?' + urllib.urlencode(payload)
logger.error('[PAYLOAD:PRESENT] Unable to download nzb from link: %s [%s]' % (errorlink, link))
return "sab-fail"
else:
#convert to a generic type of format to help with post-processing.
filen = re.sub("\&", 'and', filen)
filen = re.sub('[\,\:\?\']', '', filen)
filen = re.sub('[\(\)]', ' ', filen)
filen = re.sub('[\s\s+]', '', filen) #make sure we remove the extra spaces.
logger.fdebug('[FILENAME] filename (remove chars): %s' % filen)
filen = re.sub('.cbr', '', filen).strip()
filen = re.sub('.cbz', '', filen).strip()
logger.fdebug('[FILENAME] nzbname (\s): %s' % filen)
#filen = re.sub('\s', '.', filen)
logger.fdebug('[FILENAME] end nzbname: %s' % filen)
if re.sub('.nzb', '', filen.lower()).strip() != re.sub('.nzb', '', nzbname.lower()).strip():
alt_nzbname = re.sub('.nzb', '', filen).strip()
alt_nzbname = re.sub('[\s+]', ' ', alt_nzbname)
alt_nzbname = re.sub('[\s\_]', '.', alt_nzbname)
logger.info('filen: %s -- nzbname: %s are not identical. Storing extra value as : %s' % (filen, nzbname, alt_nzbname))
#make sure the cache directory exists - if not, create it (used for storing nzbs).
if os.path.exists(mylar.CONFIG.CACHE_DIR):
if mylar.CONFIG.ENFORCE_PERMS:
logger.fdebug('Cache Directory successfully found at : %s. Ensuring proper permissions.' % mylar.CONFIG.CACHE_DIR)
#enforce the permissions here to ensure the lower portion writes successfully
filechecker.setperms(mylar.CONFIG.CACHE_DIR, True)
else:
logger.fdebug('Cache Directory successfully found at : %s' % mylar.CONFIG.CACHE_DIR)
else:
#let's make the dir.
logger.fdebug('Could not locate Cache Directory, attempting to create at : %s' % mylar.CONFIG.CACHE_DIR)
try:
filechecker.validateAndCreateDirectory(mylar.CONFIG.CACHE_DIR, True)
logger.info('Temporary NZB Download Directory successfully created at: %s' % mylar.CONFIG.CACHE_DIR)
except OSError:
raise
#save the nzb grabbed, so we can bypass all the 'send-url' crap.
if not nzbname.endswith('.nzb'):
nzbname = nzbname + '.nzb'
nzbpath = os.path.join(mylar.CONFIG.CACHE_DIR, nzbname)
with open(nzbpath, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
#blackhole
sent_to = None
t_hash = None
if mylar.CONFIG.ENABLE_DDL is True and nzbprov == 'ddl':
if all([IssueID is None, IssueArcID is not None]):
tmp_issueid = IssueArcID
else:
tmp_issueid = IssueID
ggc = getcomics.GC(issueid=tmp_issueid, comicid=ComicID)
sendsite = ggc.loadsite(nzbid, link)
ddl_it = ggc.parse_downloadresults(nzbid, link)
if ddl_it['success'] is True:
logger.info('Successfully snatched %s from DDL site. It is currently being queued to download in position %s' % (nzbname, mylar.DDL_QUEUE.qsize()))
else:
logger.info('Failed to retrieve %s from the DDL site.' % nzbname)
return "ddl-fail"
sent_to = "is downloading it directly via DDL"
elif mylar.USE_BLACKHOLE and all([nzbprov != '32P', nzbprov != 'WWT', nzbprov != 'DEM', nzbprov != 'torznab']):
logger.fdebug('Using blackhole directory at : %s' % mylar.CONFIG.BLACKHOLE_DIR)
if os.path.exists(mylar.CONFIG.BLACKHOLE_DIR):
#copy the nzb from nzbpath to blackhole dir.
try:
shutil.move(nzbpath, os.path.join(mylar.CONFIG.BLACKHOLE_DIR, nzbname))
except (OSError, IOError):
logger.warn('Failed to move nzb into blackhole directory - check blackhole directory and/or permissions.')
return "blackhole-fail"
logger.fdebug('Filename saved to your blackhole as : %s' % nzbname)
logger.info('Successfully sent .nzb to your Blackhole directory : %s' % os.path.join(mylar.CONFIG.BLACKHOLE_DIR, nzbname))
sent_to = "has sent it to your Blackhole Directory"
if mylar.CONFIG.ENABLE_SNATCH_SCRIPT:
if comicinfo[0]['pack'] is False:
pnumbers = None
plist = None
else:
pnumbers = '|'.join(comicinfo[0]['pack_numbers'])
plist= '|'.join(comicinfo[0]['pack_issuelist'])
snatch_vars = {'nzbinfo': {'link': link,
'id': nzbid,
'nzbname': nzbname,
'nzbpath': nzbpath,
'blackhole': mylar.CONFIG.BLACKHOLE_DIR},
'comicinfo': {'comicname': ComicName,
'volume': comicinfo[0]['ComicVolume'],
'comicid': ComicID,
'issueid': IssueID,
'issuearcid': IssueArcID,
'issuenumber': IssueNumber,
'issuedate': comicinfo[0]['IssueDate'],
'seriesyear': comyear},
'pack': comicinfo[0]['pack'],
'pack_numbers': pnumbers,
'pack_issuelist': plist,
'provider': nzbprov,
'method': 'nzb',
'clientmode': 'blackhole'}
snatchitup = helpers.script_env('on-snatch',snatch_vars)
if snatchitup is True:
logger.info('Successfully submitted on-grab script as requested.')
else:
logger.info('Could not Successfully submit on-grab script as requested. Please check logs...')
#end blackhole
#torrents (32P & DEM)
elif any([nzbprov == '32P', nzbprov == 'WWT', nzbprov == 'DEM', nzbprov == 'torznab']):
logger.fdebug('ComicName: %s' % ComicName)
logger.fdebug('link: %s' % link)
logger.fdebug('Torrent Provider: %s' % nzbprov)
rcheck = rsscheck.torsend2client(ComicName, IssueNumber, comyear, link, nzbprov, nzbid) #nzbid = hash for usage with public torrents
if rcheck == "fail":
if mylar.CONFIG.FAILED_DOWNLOAD_HANDLING:
logger.error('Unable to send torrent to client. Assuming incomplete link - sending to Failed Handler and continuing search.')
if any([oneoff is True, IssueID is None]):
logger.fdebug('One-off mode was initiated - Failed Download handling for : %s #%s' % (ComicName, IssueNumber))
comicinfo = {"ComicName": ComicName,
"IssueNumber": IssueNumber}
else:
comicinfo_temp = {"ComicName": comicinfo[0]['ComicName'],
"modcomicname": comicinfo[0]['modcomicname'],
"IssueNumber": comicinfo[0]['IssueNumber'],
"comyear": comicinfo[0]['comyear']}
comicinfo = comicinfo_temp
return FailedMark(ComicID=ComicID, IssueID=IssueID, id=nzbid, nzbname=nzbname, prov=nzbprov, oneoffinfo=comicinfo)
else:
logger.error('Unable to send torrent - check logs and settings (this would be marked as a BAD torrent if Failed Handling was enabled)')
return "torrent-fail"
else:
#start the auto-snatch segway here (if rcheck isn't False, it contains the info of the torrent)
#since this is torrentspecific snatch, the vars will be different than nzb snatches.
#torrent_info{'folder','name',['total_filesize','label','hash','files','time_started'}
t_hash = rcheck['hash']
rcheck.update({'torrent_filename': nzbname})
if any([mylar.USE_RTORRENT, mylar.USE_DELUGE]) and mylar.CONFIG.AUTO_SNATCH:
mylar.SNATCHED_QUEUE.put(rcheck['hash'])
elif any([mylar.USE_RTORRENT, mylar.USE_DELUGE]) and mylar.CONFIG.LOCAL_TORRENT_PP:
mylar.SNATCHED_QUEUE.put(rcheck['hash'])
else:
if mylar.CONFIG.ENABLE_SNATCH_SCRIPT:
try:
if comicinfo[0]['pack'] is False:
pnumbers = None
plist = None
else:
if '0-Day Comics Pack' in ComicName:
helpers.lookupthebitches(rcheck['files'], rcheck['folder'], nzbname, nzbid, nzbprov, t_hash, comicinfo[0]['IssueDate'])
pnumbers = None
plist = None
else:
pnumbers = '|'.join(comicinfo[0]['pack_numbers'])
plist = '|'.join(comicinfo[0]['pack_issuelist'])
snatch_vars = {'comicinfo': {'comicname': ComicName,
'volume': comicinfo[0]['ComicVolume'],
'issuenumber': IssueNumber,
'issuedate': comicinfo[0]['IssueDate'],
'seriesyear': comyear,
'comicid': ComicID,
'issueid': IssueID,
'issuearcid': IssueArcID},
'pack': comicinfo[0]['pack'],
'pack_numbers': pnumbers,
'pack_issuelist': plist,
'provider': nzbprov,
'method': 'torrent',
'clientmode': rcheck['clientmode'],
'torrentinfo': rcheck}
snatchitup = helpers.script_env('on-snatch',snatch_vars)
if snatchitup is True:
logger.info('Successfully submitted on-grab script as requested.')
else:
logger.info('Could not Successfully submit on-grab script as requested. Please check logs...')
except Exception as e:
logger.warn('error: %s' % e)
if mylar.USE_WATCHDIR is True:
if mylar.CONFIG.TORRENT_LOCAL is True:
sent_to = "has sent it to your local Watch folder"
else:
sent_to = "has sent it to your seedbox Watch folder"
elif mylar.USE_UTORRENT is True:
sent_to = "has sent it to your uTorrent client"
elif mylar.USE_RTORRENT is True:
sent_to = "has sent it to your rTorrent client"
elif mylar.USE_TRANSMISSION is True:
sent_to = "has sent it to your Transmission client"
elif mylar.USE_DELUGE is True:
sent_to = "has sent it to your Deluge client"
elif mylar.USE_QBITTORRENT is True:
sent_to = "has sent it to your qBittorrent client"
#end torrents
else:
#SABnzbd / NZBGet
#logger.fdebug("link to retrieve via api:" + str(helpers.apiremove(linkapi,'$')))
#nzb.get
if mylar.USE_NZBGET:
ss = nzbget.NZBGet()
send_to_nzbget = ss.sender(nzbpath)
if mylar.CONFIG.NZBGET_CLIENT_POST_PROCESSING is True:
if send_to_nzbget['status'] is True:
send_to_nzbget['comicid'] = ComicID
if IssueID is not None:
send_to_nzbget['issueid'] = IssueID
else:
send_to_nzbget['issueid'] = 'S' + IssueArcID
send_to_nzbget['apicall'] = True
mylar.NZB_QUEUE.put(send_to_nzbget)
elif send_to_nzbget['status'] == 'double-pp':
return send_to_nzbget['status']
else:
logger.warn('Unable to send nzb file to NZBGet. There was a parameter error as there are no values present: %s' % nzbget_params)
return "nzbget-fail"
if send_to_nzbget['status'] is True:
logger.info("Successfully sent nzb to NZBGet!")
else:
logger.info("Unable to send nzb to NZBGet - check your configs.")
return "nzbget-fail"
sent_to = "has sent it to your NZBGet"
#end nzb.get
elif mylar.USE_SABNZBD:
sab_params = None
# let's build the send-to-SAB string now:
# changed to just work with direct links now...
#generate the api key to download here and then kill it immediately after.
if mylar.DOWNLOAD_APIKEY is None:
import hashlib, random
mylar.DOWNLOAD_APIKEY = hashlib.sha224(str(random.getrandbits(256))).hexdigest()[0:32]
#generate the mylar host address if applicable.
if mylar.CONFIG.ENABLE_HTTPS:
proto = 'https://'
else:
proto = 'http://'
if mylar.CONFIG.HTTP_ROOT is None:
hroot = '/'
elif mylar.CONFIG.HTTP_ROOT.endswith('/'):
hroot = mylar.CONFIG.HTTP_ROOT
else:
if mylar.CONFIG.HTTP_ROOT != '/':
hroot = mylar.CONFIG.HTTP_ROOT + '/'
else:
hroot = mylar.CONFIG.HTTP_ROOT
if mylar.LOCAL_IP is None:
#if mylar's local, get the local IP using socket.
try:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
mylar.LOCAL_IP = s.getsockname()[0]
s.close()
except:
logger.warn('Unable to determine local IP. Defaulting to host address for Mylar provided as : %s' % mylar.CONFIG.HTTP_HOST)
if mylar.CONFIG.HOST_RETURN:
#mylar has the return value already provided (easier and will work if it's right)
if mylar.CONFIG.HOST_RETURN.endswith('/'):
mylar_host = mylar.CONFIG.HOST_RETURN
else:
mylar_host = mylar.CONFIG.HOST_RETURN + '/'
elif mylar.CONFIG.SAB_TO_MYLAR:
#if sab & mylar are on different machines, check to see if they are local or external IP's provided for host.
if mylar.CONFIG.HTTP_HOST == 'localhost' or mylar.CONFIG.HTTP_HOST == '0.0.0.0' or mylar.CONFIG.HTTP_HOST.startswith('10.') or mylar.CONFIG.HTTP_HOST.startswith('192.') or mylar.CONFIG.HTTP_HOST.startswith('172.'):
#if mylar's local, use the local IP already assigned to LOCAL_IP.
mylar_host = proto + str(mylar.LOCAL_IP) + ':' + str(mylar.CONFIG.HTTP_PORT) + hroot
else:
if mylar.EXT_IP is None:
#if mylar isn't local, get the external IP using pystun.
import stun
sip = mylar.CONFIG.HTTP_HOST
port = int(mylar.CONFIG.HTTP_PORT)
try:
nat_type, ext_ip, ext_port = stun.get_ip_info(sip,port)
mylar_host = proto + str(ext_ip) + ':' + str(mylar.CONFIG.HTTP_PORT) + hroot
mylar.EXT_IP = ext_ip
except:
logger.warn('Unable to retrieve External IP - try using the host_return option in the config.ini.')
mylar_host = proto + str(mylar.CONFIG.HTTP_HOST) + ':' + str(mylar.CONFIG.HTTP_PORT) + hroot
else:
mylar_host = proto + str(mylar.EXT_IP) + ':' + str(mylar.CONFIG.HTTP_PORT) + hroot
else:
#if all else fails, drop it back to the basic host:port and try that.
if mylar.LOCAL_IP is None:
tmp_host = mylar.CONFIG.HTTP_HOST
else:
tmp_host = mylar.LOCAL_IP
mylar_host = proto + str(tmp_host) + ':' + str(mylar.CONFIG.HTTP_PORT) + hroot
fileURL = mylar_host + 'api?apikey=' + mylar.DOWNLOAD_APIKEY + '&cmd=downloadNZB&nzbname=' + nzbname
sab_params = {'apikey': mylar.CONFIG.SAB_APIKEY,
'mode': 'addurl',
'name': fileURL,
'cmd': 'downloadNZB',
'nzbname': nzbname,
'output': 'json'}
# determine SAB priority
if mylar.CONFIG.SAB_PRIORITY:
#setup the priorities.
if mylar.CONFIG.SAB_PRIORITY == "Default": sabpriority = "-100"
elif mylar.CONFIG.SAB_PRIORITY == "Low": sabpriority = "-1"
elif mylar.CONFIG.SAB_PRIORITY == "Normal": sabpriority = "0"
elif mylar.CONFIG.SAB_PRIORITY == "High": sabpriority = "1"
elif mylar.CONFIG.SAB_PRIORITY == "Paused": sabpriority = "-2"
else:
#if sab priority isn't selected, default to Normal (0)
sabpriority = "0"
sab_params['priority'] = sabpriority
# if category is blank, let's adjust
if mylar.CONFIG.SAB_CATEGORY:
sab_params['cat'] = mylar.CONFIG.SAB_CATEGORY
#if mylar.CONFIG.POST_PROCESSING: #or mylar.CONFIG.RENAME_FILES:
# if mylar.CONFIG.POST_PROCESSING_SCRIPT:
# #this is relative to the SABnzbd script directory (ie. no path)
# tmpapi = tmpapi + "&script=" + mylar.CONFIG.POST_PROCESSING_SCRIPT
# else:
# tmpapi = tmpapi + "&script=ComicRN.py"
# logger.fdebug("...attaching rename script: " + str(helpers.apiremove(tmpapi, '&')))
#final build of send-to-SAB
#logger.fdebug("Completed send-to-SAB link: " + str(helpers.apiremove(tmpapi, '&')))
if sab_params is not None:
ss = sabnzbd.SABnzbd(sab_params)
sendtosab = ss.sender()
if all([sendtosab['status'] is True, mylar.CONFIG.SAB_CLIENT_POST_PROCESSING is True]):
sendtosab['comicid'] = ComicID
if IssueID is not None:
sendtosab['issueid'] = IssueID
else:
sendtosab['issueid'] = 'S' + IssueArcID
sendtosab['apicall'] = True
logger.info('sendtosab: %s' % sendtosab)
mylar.NZB_QUEUE.put(sendtosab)
elif sendtosab['status'] == 'double-pp':
return sendtosab['status']
elif sendtosab['status'] is False:
return "sab-fail"
else:
logger.warn('Unable to send nzb file to SABnzbd. There was a parameter error as there are no values present: %s' % sab_params)
mylar.DOWNLOAD_APIKEY = None
return "sab-fail"
sent_to = "has sent it to your SABnzbd+"
logger.info(u"Successfully sent nzb file to SABnzbd")
if mylar.CONFIG.ENABLE_SNATCH_SCRIPT:
if mylar.USE_NZBGET:
clientmode = 'nzbget'
client_id = '%s' % send_to_nzbget['NZBID']
elif mylar.USE_SABNZBD:
clientmode = 'sabnzbd'
client_id = sendtosab['nzo_id']
if comicinfo[0]['pack'] is False:
pnumbers = None
plist = None
else:
pnumbers = '|'.join(comicinfo[0]['pack_numbers'])
plist= '|'.join(comicinfo[0]['pack_issuelist'])
snatch_vars = {'nzbinfo': {'link': link,
'id': nzbid,
'client_id': client_id,
'nzbname': nzbname,
'nzbpath': nzbpath},
'comicinfo': {'comicname': comicinfo[0]['ComicName'].encode('utf-8'),
'volume': comicinfo[0]['ComicVolume'],
'comicid': ComicID,
'issueid': IssueID,
'issuearcid': IssueArcID,
'issuenumber': IssueNumber,
'issuedate': comicinfo[0]['IssueDate'],
'seriesyear': comyear},
'pack': comicinfo[0]['pack'],
'pack_numbers': pnumbers,
'pack_issuelist': plist,
'provider': nzbprov,
'method': 'nzb',
'clientmode': clientmode}
snatchitup = helpers.script_env('on-snatch',snatch_vars)
if snatchitup is True:
logger.info('Successfully submitted on-grab script as requested.')
else:
logger.info('Could not Successfully submit on-grab script as requested. Please check logs...')
#nzbid, nzbname, sent_to
nzbname = re.sub('.nzb', '', nzbname).strip()
return_val = {}
return_val = {"nzbid": nzbid,
"nzbname": nzbname,
"sent_to": sent_to,
"SARC": SARC,
"alt_nzbname": alt_nzbname,
"t_hash": t_hash}
#if it's a directsend link (ie. via a retry).
if directsend is None:
return return_val
else:
if 'Public Torrents' in tmpprov and any([nzbprov == 'WWT', nzbprov == 'DEM']):
tmpprov = re.sub('Public Torrents', nzbprov, tmpprov)
#update the db on the snatch.
if alt_nzbname is None or alt_nzbname == '':
logger.fdebug("Found matching comic...preparing to send to Updater with IssueID %s and nzbname of %s [Oneoff:%s]" % (IssueID, nzbname, oneoff))
if '[RSS]' in tmpprov: tmpprov = re.sub('\[RSS\]', '', tmpprov).strip()
updater.nzblog(IssueID, nzbname, ComicName, SARC=SARC, IssueArcID=IssueArcID, id=nzbid, prov=tmpprov, oneoff=oneoff)
else:
logger.fdebug("Found matching comic...preparing to send to Updater with IssueID %s and nzbname of %s [ALTNZBNAME:%s][OneOff:%s]" % (IssueID, nzbname, alt_nzbname, oneoff))
if '[RSS]' in tmpprov: tmpprov = re.sub('\[RSS\]', '', tmpprov).strip()
updater.nzblog(IssueID, nzbname, ComicName, SARC=SARC, IssueArcID=IssueArcID, id=nzbid, prov=tmpprov, alt_nzbname=alt_nzbname, oneoff=oneoff)
#send out notifications for on snatch after the updater incase notification fails (it would bugger up the updater/pp scripts)
notify_snatch(sent_to, ComicName, comyear, IssueNumber, nzbprov, False)
mylar.TMP_PROV = nzbprov
return return_val
def notify_snatch(sent_to, comicname, comyear, IssueNumber, nzbprov, pack):
if pack is False:
snline = 'Issue snatched!'
else:
snline = 'Pack snatched!'
if IssueNumber is not None:
snatched_name = '%s (%s) #%s' % (comicname, comyear, IssueNumber)
else:
snatched_name= '%s (%s)' % (comicname, comyear)
if mylar.CONFIG.PROWL_ENABLED and mylar.CONFIG.PROWL_ONSNATCH:
logger.info(u"Sending Prowl notification")
prowl = notifiers.PROWL()
prowl.notify(snatched_name, 'Download started using %s' % sent_to)
if mylar.CONFIG.PUSHOVER_ENABLED and mylar.CONFIG.PUSHOVER_ONSNATCH:
logger.info(u"Sending Pushover notification")
pushover = notifiers.PUSHOVER()
pushover.notify(snline, snatched_nzb=snatched_name, prov=nzbprov, sent_to=sent_to)
if mylar.CONFIG.BOXCAR_ENABLED and mylar.CONFIG.BOXCAR_ONSNATCH:
logger.info(u"Sending Boxcar notification")
boxcar = notifiers.BOXCAR()
boxcar.notify(snatched_nzb=snatched_name, sent_to=sent_to, snline=snline)
if mylar.CONFIG.PUSHBULLET_ENABLED and mylar.CONFIG.PUSHBULLET_ONSNATCH:
logger.info(u"Sending Pushbullet notification")
pushbullet = notifiers.PUSHBULLET()
pushbullet.notify(snline=snline, snatched=snatched_name, sent_to=sent_to, prov=nzbprov, method='POST')
if mylar.CONFIG.TELEGRAM_ENABLED and mylar.CONFIG.TELEGRAM_ONSNATCH:
logger.info(u"Sending Telegram notification")
telegram = notifiers.TELEGRAM()
telegram.notify("%s - %s - Mylar %s" % (snline, snatched_name, sent_to))
if mylar.CONFIG.SLACK_ENABLED and mylar.CONFIG.SLACK_ONSNATCH:
logger.info(u"Sending Slack notification")
slack = notifiers.SLACK()
slack.notify("Snatched", snline, snatched_nzb=snatched_name, sent_to=sent_to, prov=nzbprov)
if mylar.CONFIG.EMAIL_ENABLED and mylar.CONFIG.EMAIL_ONGRAB:
logger.info(u"Sending email notification")
email = notifiers.EMAIL()
email.notify(snline + " - " + snatched_name, "Mylar notification - Snatch", module="[SEARCH]")
return
def FailedMark(IssueID, ComicID, id, nzbname, prov, oneoffinfo=None):
# Used to pass a failed attempt at sending a download to a client, to the failed handler, and then back again to continue searching.
from mylar import Failed
FailProcess = Failed.FailedProcessor(issueid=IssueID, comicid=ComicID, id=id, nzb_name=nzbname, prov=prov, oneoffinfo=oneoffinfo)
Markit = FailProcess.markFailed()
if prov == '32P' or prov == 'Public Torrents': return "torrent-fail"
else: return "downloadchk-fail"
def IssueTitleCheck(issuetitle, watchcomic_split, splitit, splitst, issue_firstword, hyphensplit, orignzb=None):
vals = []
initialchk = 'ok'
isstitle_chk = False
logger.fdebug("incorrect comic lengths...not a match")
issuetitle = re.sub('[\-\:\,\?\.]', ' ', str(issuetitle))
issuetitle_words = issuetitle.split(None)
#issue title comparison here:
logger.fdebug('there are %s words in the issue title of : %s' % (len(issuetitle_words), issuetitle))
# we minus 1 the splitst since the issue # is included in there.
if (splitst - 1) > len(watchcomic_split):
logger.fdebug('splitit:' + str(splitit))
logger.fdebug('splitst:' + str(splitst))
logger.fdebug('len-watchcomic:' + str(len(watchcomic_split)))
possibleissue_num = splitit[len(watchcomic_split)] #[splitst]
logger.fdebug('possible issue number of : %s' % possibleissue_num)
extra_words = splitst - len(watchcomic_split)
logger.fdebug('there are %s left over after we remove the series title.' % extra_words)
wordcount = 1
#remove the series title here so we just have the 'hopefully' issue title
for word in splitit:
#logger.info('word: ' + str(word))
if wordcount > len(watchcomic_split):
#logger.info('wordcount: ' + str(wordcount))
#logger.info('watchcomic_split: ' + str(len(watchcomic_split)))
if wordcount - len(watchcomic_split) == 1:
search_issue_title = word
possibleissue_num = word
else:
search_issue_title += ' ' + word
wordcount +=1
decit = search_issue_title.split(None)
if decit[0].isdigit() and decit[1].isdigit():
logger.fdebug('possible decimal - referencing position from original title.')
chkme = orignzb.find(decit[0])
chkend = orignzb.find(decit[1], chkme + len(decit[0]))
chkspot = orignzb[chkme:chkend +1]
print chkme, chkend
print chkspot
# we add +1 to decit totals in order to account for the '.' that's missing and we assume is there.
if len(chkspot) == (len(decit[0]) + len(decit[1]) + 1):
logger.fdebug('lengths match for possible decimal issue.')
if '.' in chkspot:
logger.fdebug('decimal located within : %s' % chkspot)
possibleissue_num = chkspot
splitst = splitst -1 #remove the second numeric as it's a decimal and would add an extra char to
logger.fdebug('search_issue_title is : %s' % search_issue_title)
logger.fdebug('possible issue number of : %s' % possibleissue_num)
if hyphensplit is not None and 'of' not in search_issue_title:
logger.fdebug('hypen split detected.')
try:
issue_start = search_issue_title.find(issue_firstword)
logger.fdebug('located first word of : %s at position : %s' % (issue_firstword, issue_start))
search_issue_title = search_issue_title[issue_start:]
logger.fdebug('corrected search_issue_title is now : %s' % search_issue_title)
except TypeError:
logger.fdebug('invalid parsing detection. Ignoring this result.')
return vals.append({"splitit": splitit,
"splitst": splitst,
"isstitle_chk": isstitle_chk,
"status": "continue"})
#now we have the nzb issue title (if it exists), let's break it down further.
sit_split = search_issue_title.split(None)
watch_split_count = len(issuetitle_words)
isstitle_removal = []
isstitle_match = 0 #counter to tally % match
misword = 0 # counter to tally words that probably don't need to be an 'exact' match.
for wsplit in issuetitle_words:
of_chk = False
if wsplit.lower() == 'part' or wsplit.lower() == 'of':
if wsplit.lower() == 'of':
of_chk = True
logger.fdebug('not worrying about this word : %s' % wsplit)
misword +=1
continue
if wsplit.isdigit() and of_chk == True:
logger.fdebug('of %s detected. Ignoring for matching.' % wsplit)
of_chk = False
continue
for sit in sit_split:
logger.fdebug('looking at : %s -TO- %s' % (sit.lower(), wsplit.lower()))
if sit.lower() == 'part':
logger.fdebug('not worrying about this word : %s' % sit)
misword +=1
isstitle_removal.append(sit)
break
elif sit.lower() == wsplit.lower():
logger.fdebug('word match: %s' % sit)
isstitle_match +=1
isstitle_removal.append(sit)
break
else:
try:
if int(sit) == int(wsplit):
logger.fdebug('found matching numeric: %s' % wsplit)
isstitle_match +=1
isstitle_removal.append(sit)
break
except:
pass
logger.fdebug('isstitle_match count : %s' % isstitle_match)
if isstitle_match > 0:
iss_calc = ((isstitle_match + misword) / watch_split_count) * 100
logger.fdebug('iss_calc: %s %s with %s unaccounted for words' % (iss_calc, '%', misword))
else:
iss_calc = 0
logger.fdebug('0 words matched on issue title.')
if iss_calc >= 80: #mylar.ISSUE_TITLEMATCH - user-defined percentage to match against for issue name comparisons.
logger.fdebug('>80% match on issue name. If this were implemented, this would be considered a match.')
logger.fdebug('we should remove %s words : %s' % (len(isstitle_removal), isstitle_removal))
logger.fdebug('Removing issue title from nzb filename to improve matching algorithims.')
splitst = splitst - len(isstitle_removal)
isstitle_chk = True
vals.append({"splitit": splitit,
"splitst": splitst,
"isstitle_chk": isstitle_chk,
"possibleissue_num": possibleissue_num,
"isstitle_removal": isstitle_removal,
"status": 'ok'})
return vals
return
def generate_id(nzbprov, link):
#logger.fdebug('[%s] generate_id - link: %s' % (nzbprov, link))
if nzbprov == 'experimental':
#id is located after the /download/ portion
url_parts = urlparse.urlparse(link)
path_parts = url_parts[2].rpartition('/')
nzbtempid = path_parts[0].rpartition('/')
nzblen = len(nzbtempid)
nzbid = nzbtempid[nzblen -1]
elif nzbprov == '32P':
#32P just has the torrent id stored.
nzbid = link
elif any([nzbprov == 'WWT', nzbprov == 'DEM']):
#if nzbprov == 'TPSE':
# #TPSE is magnet links only.
# info_hash = re.findall("urn:btih:([\w]{32,40})", link)[0]
# if len(info_hash) == 32:
# info_hash = b16encode(b32decode(info_hash))
# nzbid = info_hash.upper()
#else:
if 'http' not in link and any([nzbprov == 'WWT', nzbprov == 'DEM']):
nzbid = link
else:
#for users that already have the cache in place.
url_parts = urlparse.urlparse(link)
path_parts = url_parts[2].rpartition('/')
nzbtempid = path_parts[2]
nzbid = re.sub('.torrent', '', nzbtempid).rstrip()
elif nzbprov == 'nzb.su':
nzbid = os.path.splitext(link)[0].rsplit('/', 1)[1]
elif nzbprov == 'dognzb':
url_parts = urlparse.urlparse(link)
path_parts = url_parts[2].rpartition('/')
nzbid = path_parts[0].rsplit('/', 1)[1]
elif 'newznab' in nzbprov:
#if in format of http://newznab/getnzb/<id>.nzb&i=1&r=apikey
tmpid = urlparse.urlparse(link)[4] #param 4 is the query string from the url.
if 'searchresultid' in tmpid:
nzbid = os.path.splitext(link)[0].rsplit('searchresultid=',1)[1]
elif tmpid == '' or tmpid is None:
nzbid = os.path.splitext(link)[0].rsplit('/', 1)[1]
else:
nzbinfo = urlparse.parse_qs(link)
nzbid = nzbinfo.get('id', None)
if nzbid is not None:
nzbid = ''.join(nzbid)
if nzbid is None:
#if apikey is passed in as a parameter and the id is in the path
findend = tmpid.find('&')
if findend == -1:
findend = len(tmpid)
nzbid = tmpid[findend+1:].strip()
else:
findend = tmpid.find('apikey=', findend)
nzbid = tmpid[findend+1:].strip()
if '&id' not in tmpid or nzbid == '':
tmpid = urlparse.urlparse(link)[2]
nzbid = tmpid.rsplit('/', 1)[1]
elif nzbprov == 'torznab':
idtmp = urlparse.urlparse(link)[4]
idpos = idtmp.find('&')
nzbid = re.sub('id=', '', idtmp[:idpos]).strip()
return nzbid
| 161,475 | Python | .py | 2,708 | 40.681684 | 534 | 0.508547 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,242 | rsscheckit.py | evilhero_mylar/mylar/rsscheckit.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import datetime
import threading
import mylar
from mylar import logger, rsscheck, helpers, auth32p
rss_lock = threading.Lock()
class tehMain():
def __init__(self):
pass
def run(self, forcerss=None):
with rss_lock:
#logger.info('[RSS-FEEDS] RSS Feed Check was last run at : ' + str(mylar.SCHED_RSS_LAST))
firstrun = "no"
#check the last run of rss to make sure it's not hammering.
if mylar.SCHED_RSS_LAST is None or mylar.SCHED_RSS_LAST == '' or mylar.SCHED_RSS_LAST == '0' or forcerss == True:
logger.info('[RSS-FEEDS] RSS Feed Check Initalizing....')
firstrun = "yes"
duration_diff = 0
else:
tstamp = float(mylar.SCHED_RSS_LAST)
duration_diff = abs(helpers.utctimestamp() - tstamp)/60
#logger.fdebug('[RSS-FEEDS] Duration diff: %s' % duration_diff)
if firstrun == "no" and duration_diff < int(mylar.CONFIG.RSS_CHECKINTERVAL):
logger.fdebug('[RSS-FEEDS] RSS Check has taken place less than the threshold - not initiating at this time.')
return
helpers.job_management(write=True, job='RSS Feeds', current_run=helpers.utctimestamp(), status='Running')
mylar.RSS_STATUS = 'Running'
#logger.fdebug('[RSS-FEEDS] Updated RSS Run time to : ' + str(mylar.SCHED_RSS_LAST))
#function for looping through nzbs/torrent feeds
if mylar.CONFIG.ENABLE_TORRENT_SEARCH:
logger.info('[RSS-FEEDS] Initiating Torrent RSS Check.')
if mylar.CONFIG.ENABLE_PUBLIC:
logger.info('[RSS-FEEDS] Initiating Torrent RSS Feed Check on Demonoid / WorldWideTorrents.')
rsscheck.torrents(pickfeed='Public') #TPSE = DEM RSS Check + WWT RSS Check
if mylar.CONFIG.ENABLE_32P is True:
logger.info('[RSS-FEEDS] Initiating Torrent RSS Feed Check on 32P.')
if mylar.CONFIG.MODE_32P is False:
logger.fdebug('[RSS-FEEDS] 32P mode set to Legacy mode. Monitoring New Releases feed only.')
if any([mylar.CONFIG.PASSKEY_32P is None, mylar.CONFIG.PASSKEY_32P == '', mylar.CONFIG.RSSFEED_32P is None, mylar.CONFIG.RSSFEED_32P == '']):
logger.error('[RSS-FEEDS] Unable to validate information from provided RSS Feed. Verify that the feed provided is a current one.')
else:
rsscheck.torrents(pickfeed='1', feedinfo=mylar.KEYS_32P)
else:
logger.fdebug('[RSS-FEEDS] 32P mode set to Auth mode. Monitoring all personal notification feeds & New Releases feed')
if any([mylar.CONFIG.USERNAME_32P is None, mylar.CONFIG.USERNAME_32P == '', mylar.CONFIG.PASSWORD_32P is None]):
logger.error('[RSS-FEEDS] Unable to sign-on to 32P to validate settings. Please enter/check your username password in the configuration.')
else:
if mylar.KEYS_32P is None:
feed32p = auth32p.info32p()
feedinfo = feed32p.authenticate()
if feedinfo != "disable":
pass
else:
helpers.disable_provider('32P')
else:
feedinfo = mylar.FEEDINFO_32P
if feedinfo is None or len(feedinfo) == 0 or feedinfo == "disable":
logger.error('[RSS-FEEDS] Unable to retrieve any information from 32P for RSS Feeds. Skipping for now.')
else:
rsscheck.torrents(pickfeed='1', feedinfo=feedinfo[0])
x = 0
#assign personal feeds for 32p > +8
for fi in feedinfo:
x+=1
pfeed_32p = str(7 + x)
rsscheck.torrents(pickfeed=pfeed_32p, feedinfo=fi)
logger.info('[RSS-FEEDS] Initiating RSS Feed Check for NZB Providers.')
rsscheck.nzbs(forcerss=forcerss)
if mylar.CONFIG.ENABLE_DDL is True:
logger.info('[RSS-FEEDS] Initiating RSS Feed Check for DDL Provider.')
rsscheck.ddl(forcerss=forcerss)
logger.info('[RSS-FEEDS] RSS Feed Check/Update Complete')
logger.info('[RSS-FEEDS] Watchlist Check for new Releases')
mylar.search.searchforissue(rsscheck='yes')
logger.info('[RSS-FEEDS] Watchlist Check complete.')
if forcerss:
logger.info('[RSS-FEEDS] Successfully ran a forced RSS Check.')
helpers.job_management(write=True, job='RSS Feeds', last_run_completed=helpers.utctimestamp(), status='Waiting')
mylar.RSS_STATUS = 'Waiting'
return True
| 5,865 | Python | .py | 94 | 45.861702 | 166 | 0.576389 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,243 | rsscheck.py | evilhero_mylar/mylar/rsscheck.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import os, sys
import re
import feedparser
import requests
import cfscrape
import urlparse
import ftpsshup
from datetime import datetime, timedelta
import gzip
import time
import random
from bs4 import BeautifulSoup
from StringIO import StringIO
import mylar
from mylar import db, logger, ftpsshup, helpers, auth32p, utorrent, helpers
import torrent.clients.transmission as transmission
import torrent.clients.deluge as deluge
import torrent.clients.qbittorrent as qbittorrent
def _start_newznab_attr(self, attrsD):
context = self._getContext()
context.setdefault('newznab', feedparser.FeedParserDict())
context['newznab'].setdefault('tags', feedparser.FeedParserDict())
name = attrsD.get('name')
value = attrsD.get('value')
if name == 'category':
context['newznab'].setdefault('categories', []).append(value)
else:
context['newznab'][name] = value
feedparser._FeedParserMixin._start_newznab_attr = _start_newznab_attr
def torrents(pickfeed=None, seriesname=None, issue=None, feedinfo=None):
if pickfeed is None:
return
srchterm = None
if seriesname:
srchterm = re.sub(' ', '%20', seriesname)
if issue:
srchterm += '%20' + str(issue)
#this is for the public trackers included thus far in order to properly cycle throught the correct ones depending on the search request
# DEM = rss feed
# WWT = rss feed
#if pickfeed == 'TPSE-SEARCH':
# pickfeed = '2'
# loopit = 1
loopit = 1
if pickfeed == 'Public':
pickfeed = '999'
# since DEM is dead, just remove the loop entirely
# #we need to cycle through both DEM + WWT feeds
# loopit = 2
lp = 0
totalcount = 0
title = []
link = []
description = []
seriestitle = []
feeddata = []
myDB = db.DBConnection()
torthetpse = []
torthe32p = []
torinfo = {}
while (lp < loopit):
if lp == 0 and loopit == 2:
pickfeed = '6' #DEM RSS
elif lp == 1 and loopit == 2:
pickfeed = '999' #WWT RSS
feedtype = None
if pickfeed == "1" and mylar.CONFIG.ENABLE_32P is True: # 32pages new releases feed.
feed = 'https://32pag.es/feeds.php?feed=torrents_all&user=' + feedinfo['user'] + '&auth=' + feedinfo['auth'] + '&passkey=' + feedinfo['passkey'] + '&authkey=' + feedinfo['authkey']
feedtype = ' from the New Releases RSS Feed for comics'
verify = bool(mylar.CONFIG.VERIFY_32P)
elif pickfeed == "2" and srchterm is not None: # TP.SE search / RSS
lp+=1
continue
#feed = tpse_url + 'rss/' + str(srchterm) + '/'
#verify = bool(mylar.CONFIG.TPSE_VERIFY)
elif pickfeed == "3": # TP.SE rss feed (3101 = comics category) / non-RSS
lp+=1
continue
#feed = tpse_url + '?hl=en&safe=off&num=50&start=0&orderby=best&s=&filter=3101'
#feedtype = ' from the New Releases RSS Feed for comics from TP.SE'
#verify = bool(mylar.CONFIG.TPSE_VERIFY)
elif pickfeed == "4": #32p search
if any([mylar.CONFIG.USERNAME_32P is None, mylar.CONFIG.USERNAME_32P == '', mylar.CONFIG.PASSWORD_32P is None, mylar.CONFIG.PASSWORD_32P == '']):
logger.error('[RSS] Warning - you NEED to enter in your 32P Username and Password to use this option.')
lp=+1
continue
if mylar.CONFIG.MODE_32P is False:
logger.warn('[32P] Searching is not available in 32p Legacy mode. Switch to Auth mode to use the search functionality.')
lp=+1
continue
return
elif pickfeed == "5" and srchterm is not None: # demonoid search / non-RSS
feed = mylar.DEMURL + "files/?category=10&subcategory=All&language=0&seeded=2&external=2&query=" + str(srchterm) + "&uid=0&out=rss"
verify = bool(mylar.CONFIG.PUBLIC_VERIFY)
elif pickfeed == "6": # demonoid rss feed
feed = mylar.DEMURL + 'rss/10.xml'
feedtype = ' from the New Releases RSS Feed from Demonoid'
verify = bool(mylar.CONFIG.PUBLIC_VERIFY)
elif pickfeed == "999": #WWT rss feed
feed = mylar.WWTURL + 'rss.php?cat=132,50'
feedtype = ' from the New Releases RSS Feed from WorldWideTorrents'
verify = bool(mylar.CONFIG.PUBLIC_VERIFY)
elif int(pickfeed) >= 7 and feedinfo is not None and mylar.CONFIG.ENABLE_32P is True:
#personal 32P notification feeds.
#get the info here
feed = 'https://32pag.es/feeds.php?feed=' + feedinfo['feed'] + '&user=' + feedinfo['user'] + '&auth=' + feedinfo['auth'] + '&passkey=' + feedinfo['passkey'] + '&authkey=' + feedinfo['authkey'] + '&name=' + feedinfo['feedname']
feedtype = ' from your Personal Notification Feed : ' + feedinfo['feedname']
verify = bool(mylar.CONFIG.VERIFY_32P)
else:
logger.error('invalid pickfeed denoted...')
return
#if pickfeed == '2' or pickfeed == '3':
# picksite = 'TPSE'
#if pickfeed == '2':
# feedme = tpse.
if pickfeed == '5' or pickfeed == '6':
picksite = 'DEM'
elif pickfeed == '999':
picksite = 'WWT'
elif pickfeed == '1' or pickfeed == '4' or int(pickfeed) > 7:
picksite = '32P'
if all([pickfeed != '4', pickfeed != '3', pickfeed != '5']):
payload = None
ddos_protection = round(random.uniform(0,15),2)
time.sleep(ddos_protection)
logger.info('Now retrieving feed from %s' % picksite)
try:
headers = {'Accept-encoding': 'gzip',
'User-Agent': mylar.CV_HEADERS['User-Agent']}
cf_cookievalue = None
scraper = cfscrape.create_scraper()
if pickfeed == '999':
if all([pickfeed == '999', mylar.WWT_CF_COOKIEVALUE is None]):
try:
cf_cookievalue, cf_user_agent = scraper.get_tokens(feed, user_agent=mylar.CV_HEADERS['User-Agent'])
except Exception as e:
logger.warn('[WWT-RSSFEED] Unable to retrieve RSS properly: %s' % e)
lp+=1
continue
else:
mylar.WWT_CF_COOKIEVALUE = cf_cookievalue
cookievalue = cf_cookievalue
elif pickfeed == '999':
cookievalue = mylar.WWT_CF_COOKIEVALUE
r = scraper.get(feed, verify=verify, cookies=cookievalue, headers=headers)
else:
r = scraper.get(feed, verify=verify, headers=headers)
except Exception, e:
logger.warn('Error fetching RSS Feed Data from %s: %s' % (picksite, e))
lp+=1
continue
feedme = feedparser.parse(r.content)
#logger.info(feedme) #<-- uncomment this to see what Mylar is retrieving from the feed
i = 0
if pickfeed == '4':
for entry in searchresults['entries']:
justdigits = entry['file_size'] #size not available in follow-list rss feed
seeddigits = entry['seeders'] #number of seeders not available in follow-list rss feed
if int(seeddigits) >= int(mylar.CONFIG.MINSEEDS):
torthe32p.append({
'site': picksite,
'title': entry['torrent_seriesname'].lstrip() + ' ' + entry['torrent_seriesvol'] + ' #' + entry['torrent_seriesiss'],
'volume': entry['torrent_seriesvol'], # not stored by mylar yet.
'issue': entry['torrent_seriesiss'], # not stored by mylar yet.
'link': entry['torrent_id'], #just the id for the torrent
'pubdate': entry['pubdate'],
'size': entry['file_size'],
'seeders': entry['seeders'],
'files': entry['num_files']
})
i += 1
elif pickfeed == '3':
#TP.SE RSS FEED (parse)
pass
elif pickfeed == '5':
#DEMONOID SEARCH RESULT (parse)
pass
elif pickfeed == "999":
#try:
# feedme = feedparser.parse(feed)
#except Exception, e:
# logger.warn('Error fetching RSS Feed Data from %s: %s' % (picksite, e))
# lp+=1
# continue
#WWT / FEED
for entry in feedme.entries:
tmpsz = entry.description
tmpsz_st = tmpsz.find('Size:') + 6
if 'GB' in tmpsz[tmpsz_st:]:
szform = 'GB'
sz = 'G'
elif 'MB' in tmpsz[tmpsz_st:]:
szform = 'MB'
sz = 'M'
linkwwt = urlparse.parse_qs(urlparse.urlparse(entry.link).query)['id']
feeddata.append({
'site': picksite,
'title': entry.title,
'link': ''.join(linkwwt),
'pubdate': entry.updated,
'size': helpers.human2bytes(str(tmpsz[tmpsz_st:tmpsz.find(szform, tmpsz_st) -1]) + str(sz)) #+ 2 is for the length of the MB/GB in the size.
})
i+=1
else:
for entry in feedme['entries']:
#DEMONOID / FEED
if pickfeed == "6":
tmpsz = feedme.entries[i].description
tmpsz_st = tmpsz.find('Size')
if tmpsz_st != -1:
tmpsize = tmpsz[tmpsz_st:tmpsz_st+14]
if any(['GB' in tmpsize, 'MB' in tmpsize, 'KB' in tmpsize, 'TB' in tmpsize]):
tmp1 = tmpsz.find('MB', tmpsz_st)
if tmp1 == -1:
tmp1 = tmpsz.find('GB', tmpsz_st)
if tmp1 == -1:
tmp1 = tmpsz.find('TB', tmpsz_st)
if tmp1 == -1:
tmp1 = tmpsz.find('KB', tmpsz_st)
tmpsz_end = tmp1 + 2
tmpsz_st += 7
else:
tmpsz = tmpsz[:80] #limit it to the first 80 so it doesn't pick up alt covers mistakingly
tmpsz_st = tmpsz.rfind('|')
if tmpsz_st != -1:
tmpsz_end = tmpsz.find('<br />', tmpsz_st)
tmpsize = tmpsz[tmpsz_st:tmpsz_end] #st+14]
if any(['GB' in tmpsize, 'MB' in tmpsize, 'KB' in tmpsize, 'TB' in tmpsize]):
tmp1 = tmpsz.find('MB', tmpsz_st)
if tmp1 == -1:
tmp1 = tmpsz.find('GB', tmpsz_st)
if tmp1 == -1:
tmp1 = tmpsz.find('TB', tmpsz_st)
if tmp1 == -1:
tmp1 = tmpsz.find('KB', tmpsz_st)
tmpsz_end = tmp1 + 2
tmpsz_st += 2
if 'KB' in tmpsz[tmpsz_st:tmpsz_end]:
szform = 'KB'
sz = 'K'
elif 'GB' in tmpsz[tmpsz_st:tmpsz_end]:
szform = 'GB'
sz = 'G'
elif 'MB' in tmpsz[tmpsz_st:tmpsz_end]:
szform = 'MB'
sz = 'M'
elif 'TB' in tmpsz[tmpsz_st:tmpsz_end]:
szform = 'TB'
sz = 'T'
tsize = helpers.human2bytes(str(tmpsz[tmpsz_st:tmpsz.find(szform, tmpsz_st) -1]) + str(sz))
#timestamp is in YYYY-MM-DDTHH:MM:SS+TZ :/
dt = feedme.entries[i].updated
try:
pd = datetime.strptime(dt[0:19], '%Y-%m-%dT%H:%M:%S')
pdate = pd.strftime('%a, %d %b %Y %H:%M:%S') + ' ' + re.sub(':', '', dt[19:]).strip()
#if dt[19]=='+':
# pdate+=timedelta(hours=int(dt[20:22]), minutes=int(dt[23:]))
#elif dt[19]=='-':
# pdate-=timedelta(hours=int(dt[20:22]), minutes=int(dt[23:]))
except:
pdate = feedme.entries[i].updated
feeddata.append({
'site': picksite,
'title': feedme.entries[i].title,
'link': str(re.sub('genid=', '', urlparse.urlparse(feedme.entries[i].link)[4]).strip()),
#'link': str(urlparse.urlparse(feedme.entries[i].link)[2].rpartition('/')[0].rsplit('/',2)[2]),
'pubdate': pdate,
'size': tsize
})
#32p / FEEDS
elif pickfeed == "1" or int(pickfeed) > 7:
tmpdesc = feedme.entries[i].description
st_pub = feedme.entries[i].title.find('(')
st_end = feedme.entries[i].title.find(')')
pub = feedme.entries[i].title[st_pub +1:st_end] # +1 to not include (
#logger.fdebug('publisher: ' + re.sub("'",'', pub).strip()) #publisher sometimes is given within quotes for some reason, strip 'em.
vol_find = feedme.entries[i].title.find('vol.')
series = feedme.entries[i].title[st_end +1:vol_find].strip()
series = re.sub('&', '&', series).strip()
#logger.fdebug('series title: ' + series)
iss_st = feedme.entries[i].title.find(' - ', vol_find)
vol = re.sub('\.', '', feedme.entries[i].title[vol_find:iss_st]).strip()
#logger.fdebug('volume #: ' + str(vol))
issue = feedme.entries[i].title[iss_st +3:].strip()
#logger.fdebug('issue # : ' + str(issue))
try:
justdigits = feedme.entries[i].torrent_contentlength
except:
justdigits = '0'
seeddigits = 0
#if '0-Day Comics Pack' in series:
# logger.info('Comic Pack detected : ' + series)
# itd = True
if int(mylar.CONFIG.MINSEEDS) >= int(seeddigits):
#new releases has it as '&id', notification feeds have it as %ampid (possibly even &id
link = feedme.entries[i].link
link = re.sub('&','&', link)
link = re.sub('&','&', link)
linkst = link.find('&id')
linken = link.find('&', linkst +1)
if linken == -1:
linken = len(link)
newlink = re.sub('&id=', '', link[linkst:linken]).strip()
feeddata.append({
'site': picksite,
'title': series.lstrip() + ' ' + vol + ' #' + issue,
'volume': vol, # not stored by mylar yet.
'issue': issue, # not stored by mylar yet.
'link': newlink, #just the id for the torrent
'pubdate': feedme.entries[i].updated,
'size': justdigits
})
i += 1
if feedtype is None:
logger.info('[' + picksite + '] there were ' + str(i) + ' results..')
else:
logger.info('[' + picksite + '] there were ' + str(i) + ' results' + feedtype)
totalcount += i
lp += 1
if not seriesname:
#rss search results
rssdbupdate(feeddata, totalcount, 'torrent')
else:
#backlog (parsing) search results
if pickfeed == '4':
torinfo['entries'] = torthe32p
else:
torinfo['entries'] = torthetpse
return torinfo
return
def ddl(forcerss=False):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'}
ddl_feed = 'https://getcomics.info/feed/'
try:
r = requests.get(ddl_feed, verify=True, headers=headers)
except Exception, e:
logger.warn('Error fetching RSS Feed Data from DDL: %s' % (e))
return False
else:
if r.status_code != 200:
#typically 403 will not return results, but just catch anything other than a 200
if r.status_code == 403:
logger.warn('ERROR - status code:%s' % r.status_code)
return False
else:
logger.warn('[%s] Status code returned: %s' % (r.status_code))
return False
feedme = feedparser.parse(r.content)
results = []
for entry in feedme.entries:
soup = BeautifulSoup(entry.summary, 'html.parser')
orig_find = soup.find("p", {"style": "text-align: center;"})
i = 0
option_find = orig_find
while True: #i <= 10:
prev_option = option_find
option_find = option_find.findNext(text=True)
if 'Year' in option_find:
year = option_find.findNext(text=True)
year = re.sub('\|', '', year).strip()
else:
if 'Size' in prev_option:
size = option_find #.findNext(text=True)
if '- MB' in size: size = '0 MB'
possible_more = orig_find.next_sibling
break
i+=1
link = entry.link
title = entry.title
updated = entry.updated
if updated.endswith('+0000'):
updated = updated[:-5].strip()
tmpid = entry.id
id = tmpid[tmpid.find('=')+1:]
if 'KB' in size:
szform = 'KB'
sz = 'K'
elif 'GB' in size:
szform = 'GB'
sz = 'G'
elif 'MB' in size:
szform = 'MB'
sz = 'M'
elif 'TB' in size:
szform = 'TB'
sz = 'T'
tsize = helpers.human2bytes(re.sub('[^0-9]', '', size).strip() + sz)
#link can be referenced with the ?p=id url
results.append({'Title': title,
'Size': tsize,
'Link': id,
'Site': 'DDL',
'Pubdate': updated})
if len(results) >0:
logger.info('[RSS][DDL] %s entries have been indexed and are now going to be stored for caching.' % len(results))
rssdbupdate(results, len(results), 'ddl')
return
def nzbs(provider=None, forcerss=False):
feedthis = []
def _parse_feed(site, url, verify, payload=None):
logger.fdebug('[RSS] Fetching items from ' + site)
headers = {'User-Agent': str(mylar.USER_AGENT)}
try:
r = requests.get(url, params=payload, verify=verify, headers=headers)
except Exception, e:
logger.warn('Error fetching RSS Feed Data from %s: %s' % (site, e))
return
if r.status_code != 200:
#typically 403 will not return results, but just catch anything other than a 200
if r.status_code == 403:
return False
else:
logger.warn('[%s] Status code returned: %s' % (site, r.status_code))
if r.status_code == 503:
logger.warn('[%s] Site appears unresponsive/down. Disabling...' % (site))
return 'disable'
else:
return
feedme = feedparser.parse(r.content)
feedthis.append({"site": site,
"feed": feedme})
newznab_hosts = []
if mylar.CONFIG.NEWZNAB is True:
for newznab_host in mylar.CONFIG.EXTRA_NEWZNABS:
if str(newznab_host[5]) == '1':
newznab_hosts.append(newznab_host)
providercount = len(newznab_hosts) + int(mylar.CONFIG.EXPERIMENTAL is True) + int(mylar.CONFIG.NZBSU is True) + int(mylar.CONFIG.DOGNZB is True)
logger.fdebug('[RSS] You have enabled ' + str(providercount) + ' NZB RSS search providers.')
if providercount > 0:
if mylar.CONFIG.EXPERIMENTAL == 1:
max_entries = "250" if forcerss else "50"
params = {'sort': 'agedesc',
'max': max_entries,
'more': '1'}
check = _parse_feed('experimental', 'http://nzbindex.nl/rss/alt.binaries.comics.dcp', False, params)
if check == 'disable':
helpers.disable_provider(site)
if mylar.CONFIG.NZBSU == 1:
num_items = "&num=100" if forcerss else "" # default is 25
params = {'t': '7030',
'dl': '1',
'i': mylar.CONFIG.NZBSU_UID,
'r': mylar.CONFIG.NZBSU_APIKEY,
'num_items': num_items}
check = _parse_feed('nzb.su', 'https://api.nzb.su/rss', mylar.CONFIG.NZBSU_VERIFY, params)
if check == 'disable':
helpers.disable_provider(site)
if mylar.CONFIG.DOGNZB == 1:
num_items = "&num=100" if forcerss else "" # default is 25
params = {'t': '7030',
'r': mylar.CONFIG.DOGNZB_APIKEY,
'num_items': num_items}
check = _parse_feed('dognzb', 'https://dognzb.cr/rss.cfm', mylar.CONFIG.DOGNZB_VERIFY, params)
if check == 'disable':
helpers.disable_provider(site)
for newznab_host in newznab_hosts:
site = newznab_host[0].rstrip()
(newznabuid, _, newznabcat) = (newznab_host[4] or '').partition('#')
newznabuid = newznabuid or '1'
newznabcat = newznabcat or '7030'
if site[-10:] == '[nzbhydra]':
#to allow nzbhydra to do category search by most recent (ie. rss)
url = newznab_host[1].rstrip() + '/api'
params = {'t': 'search',
'cat': str(newznabcat),
'dl': '1',
'apikey': newznab_host[3].rstrip(),
'num': '100'}
check = _parse_feed(site, url, bool(newznab_host[2]), params)
else:
url = newznab_host[1].rstrip() + '/rss'
params = {'t': str(newznabcat),
'dl': '1',
'i': str(newznabuid),
'r': newznab_host[3].rstrip(),
'num': '100'}
check = _parse_feed(site, url, bool(newznab_host[2]), params)
if check is False and 'rss' in url[-3:]:
logger.fdebug('RSS url returning 403 error. Attempting to use API to get most recent items in lieu of RSS feed')
url = newznab_host[1].rstrip() + '/api'
params = {'t': 'search',
'cat': str(newznabcat),
'dl': '1',
'apikey': newznab_host[3].rstrip(),
'num': '100'}
check = _parse_feed(site, url, bool(newznab_host[2]), params)
if check == 'disable':
helpers.disable_provider(site, newznab=True)
feeddata = []
for ft in feedthis:
site = ft['site']
logger.fdebug('[RSS] (' + site + ') now being updated...')
for entry in ft['feed'].entries:
if site == 'dognzb':
#because the rss of dog doesn't carry the enclosure item, we'll use the newznab size value
size = 0
if 'newznab' in entry and 'size' in entry['newznab']:
size = entry['newznab']['size']
else:
# experimental, nzb.su, newznab
size = entry.enclosures[0]['length']
# Link
if site == 'experimental':
link = entry.enclosures[0]['url']
else:
# dognzb, nzb.su, newznab
link = entry.link
#Remove the API keys from the url to allow for possible api key changes
if site == 'dognzb':
link = re.sub(mylar.CONFIG.DOGNZB_APIKEY, '', link).strip()
else:
link = link[:link.find('&i=')].strip()
feeddata.append({'Site': site,
'Title': entry.title,
'Link': link,
'Pubdate': entry.updated,
'Size': size})
logger.info('[RSS] (' + site + ') ' + str(len(ft['feed'].entries)) + ' entries indexed.')
i = len(feeddata)
if i:
logger.info('[RSS] ' + str(i) + ' entries have been indexed and are now going to be stored for caching.')
rssdbupdate(feeddata, i, 'usenet')
return
def rssdbupdate(feeddata, i, type):
rsschktime = 15
myDB = db.DBConnection()
#let's add the entries into the db so as to save on searches
#also to build up the ID's ;)
for dataval in feeddata:
if type == 'torrent':
#we just store the torrent ID's now.
newVal = {"Link": dataval['link'],
"Pubdate": dataval['pubdate'],
"Site": dataval['site'],
"Size": dataval['size']}
ctrlVal = {"Title": dataval['title']}
else:
newlink = dataval['Link']
newVal = {"Link": newlink,
"Pubdate": dataval['Pubdate'],
"Site": dataval['Site'],
"Size": dataval['Size']}
ctrlVal = {"Title": dataval['Title']}
myDB.upsert("rssdb", newVal, ctrlVal)
logger.fdebug('Completed adding new data to RSS DB. Next add in ' + str(mylar.CONFIG.RSS_CHECKINTERVAL) + ' minutes')
return
def ddl_dbsearch(seriesname, issue, comicid=None, nzbprov=None, oneoff=False):
myDB = db.DBConnection()
seriesname_alt = None
if any([comicid is None, comicid == 'None', oneoff is True]):
pass
else:
snm = myDB.selectone("SELECT * FROM comics WHERE comicid=?", [comicid]).fetchone()
if snm is None:
logger.fdebug('Invalid ComicID of %s. Aborting search' % comicid)
return "no results"
else:
seriesname = snm['ComicName']
seriesname_alt = snm['AlternateSearch']
dsearch_rem1 = re.sub("\\band\\b", "%", seriesname.lower())
dsearch_rem2 = re.sub("\\bthe\\b", "%", dsearch_rem1.lower())
dsearch_removed = re.sub('\s+', ' ', dsearch_rem2)
dsearch_seriesname = re.sub('[\'\!\@\#\$\%\:\-\;\/\\=\?\&\.\s\,]', '%', dsearch_removed)
dsearch = '%' + dsearch_seriesname + '%'
dresults = myDB.select("SELECT * FROM rssdb WHERE Title like ? AND Site='DDL'", [dsearch])
ddltheinfo = []
ddlinfo = {}
if not dresults:
return "no results"
else:
for dl in dresults:
ddltheinfo.append({
'title': dl['Title'],
'link': dl['Link'],
'pubdate': dl['Pubdate'],
'site': dl['Site'],
'length': dl['Size']
})
ddlinfo['entries'] = ddltheinfo
return ddlinfo
def torrentdbsearch(seriesname, issue, comicid=None, nzbprov=None, oneoff=False):
myDB = db.DBConnection()
seriesname_alt = None
if any([comicid is None, comicid == 'None', oneoff is True]):
pass
else:
#logger.fdebug('ComicID: ' + str(comicid))
snm = myDB.selectone("SELECT * FROM comics WHERE comicid=?", [comicid]).fetchone()
if snm is None:
logger.fdebug('Invalid ComicID of ' + str(comicid) + '. Aborting search.')
return
else:
seriesname = snm['ComicName']
seriesname_alt = snm['AlternateSearch']
#remove 'and' and 'the':
tsearch_rem1 = re.sub("\\band\\b", "%", seriesname.lower())
tsearch_rem2 = re.sub("\\bthe\\b", "%", tsearch_rem1.lower())
tsearch_removed = re.sub('\s+', ' ', tsearch_rem2)
tsearch_seriesname = re.sub('[\'\!\@\#\$\%\:\-\;\/\\=\?\&\.\s\,]', '%', tsearch_removed)
if mylar.CONFIG.PREFERRED_QUALITY == 0:
tsearch = tsearch_seriesname + "%"
elif mylar.CONFIG.PREFERRED_QUALITY == 1:
tsearch = tsearch_seriesname + "%cbr%"
elif mylar.CONFIG.PREFERRED_QUALITY == 2:
tsearch = tsearch_seriesname + "%cbz%"
else:
tsearch = tsearch_seriesname + "%"
if seriesname == '0-Day Comics Pack - %s' % (issue[:4]):
#call the helper to get the month
tsearch += 'vol%s' % issue[5:7]
tsearch += '%'
tsearch += '#%s' % issue[8:10]
tsearch += '%'
#logger.fdebug('tsearch : ' + tsearch)
AS_Alt = []
tresults = []
tsearch = '%' + tsearch
if mylar.CONFIG.ENABLE_32P and nzbprov == '32P':
tresults = myDB.select("SELECT * FROM rssdb WHERE Title like ? AND Site='32P'", [tsearch])
if mylar.CONFIG.ENABLE_PUBLIC and nzbprov == 'Public Torrents':
tresults += myDB.select("SELECT * FROM rssdb WHERE Title like ? AND (Site='DEM' OR Site='WWT')", [tsearch])
#logger.fdebug('seriesname_alt:' + str(seriesname_alt))
if seriesname_alt is None or seriesname_alt == 'None':
if not tresults:
logger.fdebug('no Alternate name given. Aborting search.')
return "no results"
else:
chkthealt = seriesname_alt.split('##')
if chkthealt == 0:
AS_Alternate = seriesname_alt
AS_Alt.append(seriesname_alt)
for calt in chkthealt:
AS_Alter = re.sub('##', '', calt)
u_altsearchcomic = AS_Alter.encode('ascii', 'ignore').strip()
AS_Altrem = re.sub("\\band\\b", "", u_altsearchcomic.lower())
AS_Altrem = re.sub("\\bthe\\b", "", AS_Altrem.lower())
AS_Alternate = re.sub('[\_\#\,\/\:\;\.\-\!\$\%\+\'\&\?\@\s]', '%', AS_Altrem)
AS_Altrem_mod = re.sub('[\&]', ' ', AS_Altrem)
AS_formatrem_seriesname = re.sub('[\'\!\@\#\$\%\:\;\/\\=\?\.\,]', '', AS_Altrem_mod)
AS_formatrem_seriesname = re.sub('\s+', ' ', AS_formatrem_seriesname)
if AS_formatrem_seriesname[:1] == ' ': AS_formatrem_seriesname = AS_formatrem_seriesname[1:]
AS_Alt.append(AS_formatrem_seriesname)
if mylar.CONFIG.PREFERRED_QUALITY == 0:
AS_Alternate += "%"
elif mylar.CONFIG.PREFERRED_QUALITY == 1:
AS_Alternate += "%cbr%"
elif mylar.CONFIG.PREFERRED_QUALITY == 2:
AS_Alternate += "%cbz%"
else:
AS_Alternate += "%"
AS_Alternate = '%' + AS_Alternate
if mylar.CONFIG.ENABLE_32P and nzbprov == '32P':
tresults += myDB.select("SELECT * FROM rssdb WHERE Title like ? AND Site='32P'", [AS_Alternate])
if mylar.CONFIG.ENABLE_PUBLIC and nzbprov == 'Public Torrents':
tresults += myDB.select("SELECT * FROM rssdb WHERE Title like ? AND (Site='DEM' OR Site='WWT')", [AS_Alternate])
if not tresults:
logger.fdebug('torrent search returned no results for %s' % seriesname)
return "no results"
extensions = ('cbr', 'cbz')
tortheinfo = []
torinfo = {}
for tor in tresults:
#& have been brought into the title field incorretly occassionally - patched now, but to include those entries already in the
#cache db that have the incorrect entry, we'll adjust.
torTITLE = re.sub('&', '&', tor['Title']).strip()
#torsplit = torTITLE.split(' ')
if mylar.CONFIG.PREFERRED_QUALITY == 1:
if 'cbr' not in torTITLE:
#logger.fdebug('Quality restriction enforced [ cbr only ]. Rejecting result.')
continue
elif mylar.CONFIG.PREFERRED_QUALITY == 2:
if 'cbz' not in torTITLE:
#logger.fdebug('Quality restriction enforced [ cbz only ]. Rejecting result.')
continue
#logger.fdebug('tor-Title: ' + torTITLE)
#logger.fdebug('there are ' + str(len(torsplit)) + ' sections in this title')
i=0
if nzbprov is not None:
if nzbprov != tor['Site'] and not any([mylar.CONFIG.ENABLE_PUBLIC, tor['Site'] != 'WWT', tor['Site'] != 'DEM']):
#logger.fdebug('this is a result from ' + str(tor['Site']) + ', not the site I am looking for of ' + str(nzbprov))
continue
#0 holds the title/issue and format-type.
seriesname_mod = seriesname
foundname_mod = torTITLE #torsplit[0]
seriesname_mod = re.sub("\\band\\b", " ", seriesname_mod.lower())
foundname_mod = re.sub("\\band\\b", " ", foundname_mod.lower())
seriesname_mod = re.sub("\\bthe\\b", " ", seriesname_mod.lower())
foundname_mod = re.sub("\\bthe\\b", " ", foundname_mod.lower())
seriesname_mod = re.sub('[\&]', ' ', seriesname_mod)
foundname_mod = re.sub('[\&]', ' ', foundname_mod)
formatrem_seriesname = re.sub('[\'\!\@\#\$\%\:\;\=\?\.\,]', '', seriesname_mod)
formatrem_seriesname = re.sub('[\-]', ' ', formatrem_seriesname)
formatrem_seriesname = re.sub('[\/]', ' ', formatrem_seriesname) #not necessary since seriesname in a torrent file won't have /
formatrem_seriesname = re.sub('\s+', ' ', formatrem_seriesname)
if formatrem_seriesname[:1] == ' ': formatrem_seriesname = formatrem_seriesname[1:]
formatrem_torsplit = re.sub('[\'\!\@\#\$\%\:\;\\=\?\.\,]', '', foundname_mod)
formatrem_torsplit = re.sub('[\-]', ' ', formatrem_torsplit) #we replace the - with space so we'll get hits if differnces
formatrem_torsplit = re.sub('[\/]', ' ', formatrem_torsplit) #not necessary since if has a /, should be removed in above line
formatrem_torsplit = re.sub('\s+', ' ', formatrem_torsplit)
#logger.fdebug(str(len(formatrem_torsplit)) + ' - formatrem_torsplit : ' + formatrem_torsplit.lower())
#logger.fdebug(str(len(formatrem_seriesname)) + ' - formatrem_seriesname :' + formatrem_seriesname.lower())
if formatrem_seriesname.lower() in formatrem_torsplit.lower() or any(x.lower() in formatrem_torsplit.lower() for x in AS_Alt):
#logger.fdebug('matched to : ' + torTITLE)
#logger.fdebug('matched on series title: ' + seriesname)
titleend = formatrem_torsplit[len(formatrem_seriesname):]
titleend = re.sub('\-', '', titleend) #remove the '-' which is unnecessary
#remove extensions
titleend = re.sub('cbr', '', titleend)
titleend = re.sub('cbz', '', titleend)
titleend = re.sub('none', '', titleend)
#logger.fdebug('titleend: ' + titleend)
sptitle = titleend.split()
extra = ''
tortheinfo.append({
'title': torTITLE, #cttitle,
'link': tor['Link'],
'pubdate': tor['Pubdate'],
'site': tor['Site'],
'length': tor['Size']
})
torinfo['entries'] = tortheinfo
return torinfo
def nzbdbsearch(seriesname, issue, comicid=None, nzbprov=None, searchYear=None, ComicVersion=None, oneoff=False):
myDB = db.DBConnection()
seriesname_alt = None
if any([comicid is None, comicid == 'None', oneoff is True]):
pass
else:
snm = myDB.selectone("SELECT * FROM comics WHERE comicid=?", [comicid]).fetchone()
if snm is None:
logger.info('Invalid ComicID of ' + str(comicid) + '. Aborting search.')
return
else:
seriesname = snm['ComicName']
seriesname_alt = snm['AlternateSearch']
nsearch_seriesname = re.sub('[\'\!\@\#\$\%\:\;\/\\=\?\.\-\s]', '%', seriesname)
formatrem_seriesname = re.sub('[\'\!\@\#\$\%\:\;\/\\=\?\.]', '', seriesname)
nsearch = '%' + nsearch_seriesname + "%"
nresults = myDB.select("SELECT * FROM rssdb WHERE Title like ? AND Site=?", [nsearch, nzbprov])
if nresults is None:
logger.fdebug('nzb search returned no results for ' + seriesname)
if seriesname_alt is None:
logger.fdebug('no nzb Alternate name given. Aborting search.')
return "no results"
else:
chkthealt = seriesname_alt.split('##')
if chkthealt == 0:
AS_Alternate = AlternateSearch
for calt in chkthealt:
AS_Alternate = re.sub('##', '', calt)
AS_Alternate = '%' + AS_Alternate + "%"
nresults += myDB.select("SELECT * FROM rssdb WHERE Title like ? AND Site=?", [AS_Alternate, nzbprov])
if nresults is None:
logger.fdebug('nzb alternate name search returned no results.')
return "no results"
nzbtheinfo = []
nzbinfo = {}
if nzbprov == 'experimental':
except_list=['releases', 'gold line', 'distribution', '0-day', '0 day']
if ComicVersion:
ComVersChk = re.sub("[^0-9]", "", ComicVersion)
if ComVersChk == '':
ComVersChk = 0
else:
ComVersChk = 0
else:
ComVersChk = 0
filetype = None
if mylar.CONFIG.PREFERRED_QUALITY == 1: filetype = 'cbr'
elif mylar.CONFIG.PREFERRED_QUALITY == 2: filetype = 'cbz'
for results in nresults:
title = results['Title']
#logger.fdebug("titlesplit: " + str(title.split("\"")))
splitTitle = title.split("\"")
noYear = 'False'
_digits = re.compile('\d')
for subs in splitTitle:
#logger.fdebug(subs)
if len(subs) >= len(seriesname) and not any(d in subs.lower() for d in except_list) and bool(_digits.search(subs)) is True:
if subs.lower().startswith('for'):
# need to filter down alternate names in here at some point...
if seriesname.lower().startswith('for'):
pass
else:
#this is the crap we ignore. Continue
logger.fdebug('this starts with FOR : ' + str(subs) + '. This is not present in the series - ignoring.')
continue
if ComVersChk == 0:
noYear = 'False'
if ComVersChk != 0 and searchYear not in subs:
noYear = 'True'
noYearline = subs
if searchYear in subs and noYear == 'True':
#this would occur on the next check in the line, if year exists and
#the noYear check in the first check came back valid append it
subs = noYearline + ' (' + searchYear + ')'
noYear = 'False'
if noYear == 'False':
if filetype is not None:
if filetype not in subs.lower():
continue
nzbtheinfo.append({
'title': subs,
'link': re.sub('\/release\/', '/download/', results['Link']),
'pubdate': str(results['PubDate']),
'site': str(results['Site']),
'length': str(results['Size'])})
else:
for nzb in nresults:
# no need to parse here, just compile and throw it back ....
nzbtheinfo.append({
'title': nzb['Title'],
'link': nzb['Link'],
'pubdate': nzb['Pubdate'],
'site': nzb['Site'],
'length': nzb['Size']
})
#logger.fdebug("entered info for " + nzb['Title'])
nzbinfo['entries'] = nzbtheinfo
return nzbinfo
def torsend2client(seriesname, issue, seriesyear, linkit, site, pubhash=None):
logger.info('matched on ' + seriesname)
filename = helpers.filesafe(seriesname)
filename = re.sub(' ', '_', filename)
filename += "_" + str(issue) + "_" + str(seriesyear)
if linkit[-7:] != "torrent":
filename += ".torrent"
if any([mylar.USE_UTORRENT, mylar.USE_RTORRENT, mylar.USE_TRANSMISSION, mylar.USE_DELUGE, mylar.USE_QBITTORRENT]):
filepath = os.path.join(mylar.CONFIG.CACHE_DIR, filename)
logger.fdebug('filename for torrent set to : ' + filepath)
elif mylar.USE_WATCHDIR:
if mylar.CONFIG.TORRENT_LOCAL and mylar.CONFIG.LOCAL_WATCHDIR is not None:
filepath = os.path.join(mylar.CONFIG.LOCAL_WATCHDIR, filename)
logger.fdebug('filename for torrent set to : ' + filepath)
elif mylar.CONFIG.TORRENT_SEEDBOX and mylar.CONFIG.SEEDBOX_WATCHDIR is not None:
filepath = os.path.join(mylar.CONFIG.CACHE_DIR, filename)
logger.fdebug('filename for torrent set to : ' + filepath)
else:
logger.error('No Local Watch Directory or Seedbox Watch Directory specified. Set it and try again.')
return "fail"
cf_cookievalue = None
if site == '32P':
url = 'https://32pag.es/torrents.php'
if mylar.CONFIG.ENABLE_32P is False:
return "fail"
if mylar.CONFIG.VERIFY_32P == 1 or mylar.CONFIG.VERIFY_32P == True:
verify = True
else:
verify = False
logger.fdebug('[32P] Verify SSL set to : ' + str(verify))
if mylar.CONFIG.MODE_32P is False:
if mylar.KEYS_32P is None or mylar.CONFIG.PASSKEY_32P is None:
logger.warn('[32P] Unable to retrieve keys from provided RSS Feed. Make sure you have provided a CURRENT RSS Feed from 32P')
mylar.KEYS_32P = helpers.parse_32pfeed(mylar.FEED_32P)
if mylar.KEYS_32P is None or mylar.KEYS_32P == '':
return "fail"
else:
logger.fdebug('[32P-AUTHENTICATION] 32P (Legacy) Authentication Successful. Re-establishing keys.')
mylar.AUTHKEY_32P = mylar.KEYS_32P['authkey']
else:
logger.fdebug('[32P-AUTHENTICATION] 32P (Legacy) Authentication already done. Attempting to use existing keys.')
mylar.AUTHKEY_32P = mylar.KEYS_32P['authkey']
else:
if any([mylar.CONFIG.USERNAME_32P is None, mylar.CONFIG.USERNAME_32P == '', mylar.CONFIG.PASSWORD_32P is None, mylar.CONFIG.PASSWORD_32P == '']):
logger.error('[RSS] Unable to sign-on to 32P to validate settings and initiate download sequence. Please enter/check your username password in the configuration.')
return "fail"
elif mylar.CONFIG.PASSKEY_32P is None or mylar.AUTHKEY_32P is None or mylar.KEYS_32P is None:
logger.fdebug('[32P-AUTHENTICATION] 32P (Auth Mode) Authentication enabled. Keys have not been established yet, attempting to gather.')
feed32p = auth32p.info32p(reauthenticate=True)
feedinfo = feed32p.authenticate()
if feedinfo == "disable":
helpers.disable_provider('32P')
return "fail"
if mylar.CONFIG.PASSKEY_32P is None or mylar.AUTHKEY_32P is None or mylar.KEYS_32P is None:
logger.error('[RSS] Unable to sign-on to 32P to validate settings and initiate download sequence. Please enter/check your username password in the configuration.')
return "fail"
else:
logger.fdebug('[32P-AUTHENTICATION] 32P (Auth Mode) Authentication already done. Attempting to use existing keys.')
payload = {'action': 'download',
'torrent_pass': mylar.CONFIG.PASSKEY_32P,
'authkey': mylar.AUTHKEY_32P,
'id': linkit}
dfile = auth32p.info32p()
file_download = dfile.downloadfile(payload, filepath)
if file_download is False:
return "fail"
logger.fdebug('[%s] Saved torrent file to : %s' % (site, filepath))
elif site == 'DEM':
url = helpers.torrent_create('DEM', linkit)
if url.startswith('https'):
dem_referrer = mylar.DEMURL + 'files/download/'
else:
dem_referrer = 'http' + mylar.DEMURL[5:] + 'files/download/'
headers = {'Accept-encoding': 'gzip',
'User-Agent': str(mylar.USER_AGENT),
'Referer': dem_referrer}
logger.fdebug('Grabbing torrent from url:' + str(url))
payload = None
verify = False
elif site == 'WWT':
url = helpers.torrent_create('WWT', linkit)
if url.startswith('https'):
wwt_referrer = mylar.WWTURL
else:
wwt_referrer = 'http' + mylar.WWTURL[5:]
headers = {'Accept-encoding': 'gzip',
'User-Agent': mylar.CV_HEADERS['User-Agent'],
'Referer': wwt_referrer}
logger.fdebug('Grabbing torrent [id:' + str(linkit) + '] from url:' + str(url))
payload = {'id': linkit}
verify = False
else:
headers = {'Accept-encoding': 'gzip',
'User-Agent': str(mylar.USER_AGENT)}
url = linkit
payload = None
verify = False
if site != 'Public Torrents' and site != '32P':
if not verify:
#32P throws back an insecure warning because it can't validate against the CA. The below suppresses the message just for 32P instead of being displayed.
#disable SSL warnings - too many 'warning' messages about invalid certificates
try:
from requests.packages.urllib3 import disable_warnings
disable_warnings()
except ImportError:
#this is probably not necessary and redudant, but leaving in for the time being.
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings()
try:
from urllib3.exceptions import InsecureRequestWarning
urllib3.disable_warnings()
except ImportError:
logger.warn('[EPIC FAILURE] Cannot load the requests module')
return "fail"
try:
scraper = cfscrape.create_scraper()
if site == 'WWT':
if mylar.WWT_CF_COOKIEVALUE is None:
cf_cookievalue, cf_user_agent = scraper.get_tokens(url, user_agent=mylar.CV_HEADERS['User-Agent'])
mylar.WWT_CF_COOKIEVALUE = cf_cookievalue
r = scraper.get(url, params=payload, cookies=mylar.WWT_CF_COOKIEVALUE, verify=verify, stream=True, headers=headers)
else:
r = scraper.get(url, params=payload, verify=verify, stream=True, headers=headers)
#r = requests.get(url, params=payload, verify=verify, stream=True, headers=headers)
except Exception, e:
logger.warn('Error fetching data from %s (%s): %s' % (site, url, e))
# if site == '32P':
# logger.info('[TOR2CLIENT-32P] Retrying with 32P')
# if mylar.CONFIG.MODE_32P == 1:
# logger.info('[TOR2CLIENT-32P] Attempting to re-authenticate against 32P and poll new keys as required.')
# feed32p = auth32p.info32p(reauthenticate=True)
# feedinfo = feed32p.authenticate()
# if feedinfo == "disable":
# helpers.disable_provider('32P')
# return "fail"
# logger.debug('[TOR2CLIENT-32P] Creating CF Scraper')
# scraper = cfscrape.create_scraper()
# try:
# r = scraper.get(url, params=payload, verify=verify, allow_redirects=True)
# except Exception, e:
# logger.warn('[TOR2CLIENT-32P] Unable to GET %s (%s): %s' % (site, url, e))
# return "fail"
# else:
# logger.warn('[TOR2CLIENT-32P] Unable to authenticate using existing RSS Feed given. Make sure that you have provided a CURRENT feed from 32P')
# return "fail"
# else:
# return "fail"
if any([site == 'DEM', site == 'WWT']) and any([str(r.status_code) == '403', str(r.status_code) == '404', str(r.status_code) == '503']):
if str(r.status_code) != '503':
logger.warn('Unable to download from ' + site + ' [' + str(r.status_code) + ']')
#retry with the alternate torrent link.
url = helpers.torrent_create(site, linkit, True)
logger.fdebug('Trying alternate url: ' + str(url))
try:
r = requests.get(url, params=payload, verify=verify, stream=True, headers=headers)
except Exception, e:
return "fail"
else:
logger.warn('Cloudflare protection online for ' + site + '. Attempting to bypass...')
try:
scraper = cfscrape.create_scraper()
cf_cookievalue, cf_user_agent = cfscrape.get_cookie_string(url)
headers = {'Accept-encoding': 'gzip',
'User-Agent': cf_user_agent}
r = scraper.get(url, verify=verify, cookies=cf_cookievalue, stream=True, headers=headers)
except Exception, e:
return "fail"
if any([site == 'DEM', site == 'WWT']):
if r.headers.get('Content-Encoding') == 'gzip':
buf = StringIO(r.content)
f = gzip.GzipFile(fileobj=buf)
with open(filepath, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
logger.fdebug('[' + site + '] Saved torrent file to : ' + filepath)
else:
if site != '32P':
#tpse is magnet links only...
filepath = linkit
if mylar.USE_UTORRENT:
uTC = utorrent.utorrentclient()
#if site == 'TPSE':
# ti = uTC.addurl(linkit)
#else:
ti = uTC.addfile(filepath, filename)
if ti == 'fail':
return ti
else:
#if ti is value, it will return the hash
torrent_info = {}
torrent_info['hash'] = ti
torrent_info['clientmode'] = 'utorrent'
torrent_info['link'] = linkit
return torrent_info
elif mylar.USE_RTORRENT:
import test
rp = test.RTorrent()
torrent_info = rp.main(filepath=filepath)
if torrent_info:
torrent_info['clientmode'] = 'rtorrent'
torrent_info['link'] = linkit
return torrent_info
else:
return 'fail'
elif mylar.USE_TRANSMISSION:
try:
rpc = transmission.TorrentClient()
if not rpc.connect(mylar.CONFIG.TRANSMISSION_HOST, mylar.CONFIG.TRANSMISSION_USERNAME, mylar.CONFIG.TRANSMISSION_PASSWORD):
return "fail"
torrent_info = rpc.load_torrent(filepath)
if torrent_info:
torrent_info['clientmode'] = 'transmission'
torrent_info['link'] = linkit
return torrent_info
else:
return "fail"
except Exception as e:
logger.error(e)
return "fail"
elif mylar.USE_DELUGE:
try:
dc = deluge.TorrentClient()
if not dc.connect(mylar.CONFIG.DELUGE_HOST, mylar.CONFIG.DELUGE_USERNAME, mylar.CONFIG.DELUGE_PASSWORD):
logger.info('Not connected to Deluge!')
return "fail"
else:
logger.info('Connected to Deluge! Will try to add torrent now!')
torrent_info = dc.load_torrent(filepath)
if torrent_info:
torrent_info['clientmode'] = 'deluge'
torrent_info['link'] = linkit
return torrent_info
else:
return "fail"
logger.info('Unable to connect to Deluge!')
except Exception as e:
logger.error(e)
return "fail"
elif mylar.USE_QBITTORRENT:
try:
qc = qbittorrent.TorrentClient()
if not qc.connect(mylar.CONFIG.QBITTORRENT_HOST, mylar.CONFIG.QBITTORRENT_USERNAME, mylar.CONFIG.QBITTORRENT_PASSWORD):
logger.info('Not connected to qBittorrent - Make sure the Web UI is enabled and the port is correct!')
return "fail"
else:
logger.info('Connected to qBittorrent! Will try to add torrent now!')
torrent_info = qc.load_torrent(filepath)
if torrent_info['status'] is True:
torrent_info['clientmode'] = 'qbittorrent'
torrent_info['link'] = linkit
return torrent_info
else:
logger.info('Unable to add torrent to qBittorrent')
return "fail"
except Exception as e:
logger.error(e)
return "fail"
elif mylar.USE_WATCHDIR:
if mylar.CONFIG.TORRENT_LOCAL:
#if site == 'TPSE':
# torrent_info = {'hash': pubhash}
#else:
# #get the hash so it doesn't mess up...
torrent_info = helpers.get_the_hash(filepath)
torrent_info['clientmode'] = 'watchdir'
torrent_info['link'] = linkit
torrent_info['filepath'] = filepath
return torrent_info
else:
tssh = ftpsshup.putfile(filepath, filename)
return tssh
def delete_cache_entry(id):
myDB = db.DBConnection()
myDB.action("DELETE FROM rssdb WHERE link=? AND Site='32P'", [id])
if __name__ == '__main__':
#torrents(sys.argv[1])
#torrentdbsearch(sys.argv[1], sys.argv[2], sys.argv[3])
nzbs(provider=sys.argv[1])
| 57,247 | Python | .py | 1,114 | 36.658887 | 238 | 0.514671 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,244 | nzbget.py | evilhero_mylar/mylar/nzbget.py | #!/usr/bin/python
# This file is part of Harpoon.
#
# Harpoon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Harpoon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Harpoon. If not, see <http://www.gnu.org/licenses/>.
import optparse
import xmlrpclib
from base64 import standard_b64encode
from xml.dom.minidom import parseString
import os
import sys
import re
import time
import mylar
import logger
class NZBGet(object):
def __init__(self):
if mylar.CONFIG.NZBGET_HOST[:5] == 'https':
protocol = "https"
nzbget_host = mylar.CONFIG.NZBGET_HOST[8:]
elif mylar.CONFIG.NZBGET_HOST[:4] == 'http':
protocol = "http"
nzbget_host = mylar.CONFIG.NZBGET_HOST[7:]
url = '%s://'
val = (protocol,)
if mylar.CONFIG.NZBGET_USERNAME is not None:
url = url + '%s:'
val = val + (mylar.CONFIG.NZBGET_USERNAME,)
if mylar.CONFIG.NZBGET_PASSWORD is not None:
url = url + '%s'
val = val + (mylar.CONFIG.NZBGET_PASSWORD,)
if any([mylar.CONFIG.NZBGET_USERNAME, mylar.CONFIG.NZBGET_PASSWORD]):
url = url + '@%s:%s/xmlrpc'
else:
url = url + '%s:%s/xmlrpc'
val = val + (nzbget_host,mylar.CONFIG.NZBGET_PORT,)
self.nzb_url = (url % val)
self.server = xmlrpclib.ServerProxy(self.nzb_url) #,allow_none=True)
def sender(self, filename, test=False):
if mylar.CONFIG.NZBGET_PRIORITY:
if any([mylar.CONFIG.NZBGET_PRIORITY == 'Default', mylar.CONFIG.NZBGET_PRIORITY == 'Normal']):
nzbgetpriority = 0
elif mylar.CONFIG.NZBGET_PRIORITY == 'Low':
nzbgetpriority = -50
elif mylar.CONFIG.NZBGET_PRIORITY == 'High':
nzbgetpriority = 50
#there's no priority for "paused", so set "Very Low" and deal with that later...
elif mylar.CONFIG.NZBGET_PRIORITY == 'Paused':
nzbgetpriority = -100
else:
#if nzbget priority isn't selected, default to Normal (0)
nzbgetpriority = 0
in_file = open(filename, 'r')
nzbcontent = in_file.read()
in_file.close()
nzbcontent64 = standard_b64encode(nzbcontent)
try:
logger.fdebug('sending now to %s' % self.nzb_url)
if mylar.CONFIG.NZBGET_CATEGORY is None:
nzb_category = ''
else:
nzb_category = mylar.CONFIG.NZBGET_CATEGORY
sendresponse = self.server.append(filename, nzbcontent64, nzb_category, nzbgetpriority, False, False, '', 0, 'SCORE')
except Exception as e:
logger.warn('uh-oh: %s' % e)
return {'status': False}
else:
if sendresponse <= 0:
logger.warn('Invalid response received after sending to NZBGet: %s' % sendresponse)
return {'status': False}
else:
#sendresponse is the NZBID that we use to track the progress....
return {'status': True,
'NZBID': sendresponse}
def processor(self, nzbinfo):
nzbid = nzbinfo['NZBID']
try:
logger.fdebug('Now checking the active queue of nzbget for the download')
queueinfo = self.server.listgroups()
except Exception as e:
logger.warn('Error attempting to retrieve active queue listing: %s' % e)
return {'status': False}
else:
logger.fdebug('valid queue result returned. Analyzing...')
queuedl = [qu for qu in queueinfo if qu['NZBID'] == nzbid]
if len(queuedl) == 0:
logger.warn('Unable to locate NZBID %s in active queue. Could it be finished already ?' % nzbid)
return self.historycheck(nzbinfo)
stat = False
double_pp = False
double_type = None
while stat is False:
time.sleep(10)
queueinfo = self.server.listgroups()
queuedl = [qu for qu in queueinfo if qu['NZBID'] == nzbid]
if len(queuedl) == 0:
logger.fdebug('Item is no longer in active queue. It should be finished by my calculations')
stat = True
else:
if 'comicrn' in queuedl[0]['PostInfoText'].lower():
double_pp = True
double_type = 'ComicRN'
elif 'nzbtomylar' in queuedl[0]['PostInfoText'].lower():
double_pp = True
double_type = 'nzbToMylar'
if all([len(queuedl[0]['ScriptStatuses']) > 0, double_pp is False]):
for x in queuedl[0]['ScriptStatuses']:
if 'comicrn' in x['Name'].lower():
double_pp = True
double_type = 'ComicRN'
break
elif 'nzbtomylar' in x['Name'].lower():
double_pp = True
double_type = 'nzbToMylar'
break
if all([len(queuedl[0]['Parameters']) > 0, double_pp is False]):
for x in queuedl[0]['Parameters']:
if all(['comicrn' in x['Name'].lower(), x['Value'] == 'yes']):
double_pp = True
double_type = 'ComicRN'
break
elif all(['nzbtomylar' in x['Name'].lower(), x['Value'] == 'yes']):
double_pp = True
double_type = 'nzbToMylar'
break
if double_pp is True:
logger.warn('%s has been detected as being active for this category & download. Completed Download Handling will NOT be performed due to this.' % double_type)
logger.warn('Either disable Completed Download Handling for NZBGet within Mylar, or remove %s from your category script in NZBGet.' % double_type)
return {'status': 'double-pp', 'failed': False}
logger.fdebug('status: %s' % queuedl[0]['Status'])
logger.fdebug('name: %s' % queuedl[0]['NZBName'])
logger.fdebug('FileSize: %sMB' % queuedl[0]['FileSizeMB'])
logger.fdebug('Download Left: %sMB' % queuedl[0]['RemainingSizeMB'])
logger.fdebug('health: %s' % (queuedl[0]['Health']/10))
logger.fdebug('destination: %s' % queuedl[0]['DestDir'])
logger.fdebug('File has now downloaded!')
time.sleep(5) #wait some seconds so shit can get written to history properly
return self.historycheck(nzbinfo)
def historycheck(self, nzbinfo):
nzbid = nzbinfo['NZBID']
history = self.server.history(True)
found = False
destdir = None
double_pp = False
hq = [hs for hs in history if hs['NZBID'] == nzbid and ('SUCCESS' in hs['Status'] or ('COPY' in hs['Status']))]
if len(hq) > 0:
logger.fdebug('found matching completed item in history. Job has a status of %s' % hq[0]['Status'])
if len(hq[0]['ScriptStatuses']) > 0:
for x in hq[0]['ScriptStatuses']:
if 'comicrn' in x['Name'].lower():
double_pp = True
break
if all([len(hq[0]['Parameters']) > 0, double_pp is False]):
for x in hq[0]['Parameters']:
if all(['comicrn' in x['Name'].lower(), x['Value'] == 'yes']):
double_pp = True
break
if double_pp is True:
logger.warn('ComicRN has been detected as being active for this category & download. Completed Download Handling will NOT be performed due to this.')
logger.warn('Either disable Completed Download Handling for NZBGet within Mylar, or remove ComicRN from your category script in NZBGet.')
return {'status': 'double-pp', 'failed': False}
if all(['SUCCESS' in hq[0]['Status'], (hq[0]['FileSizeMB']*.95) <= hq[0]['DownloadedSizeMB'] <= (hq[0]['FileSizeMB']*1.05)]):
logger.fdebug('%s has final file size of %sMB' % (hq[0]['Name'], hq[0]['DownloadedSizeMB']))
if os.path.isdir(hq[0]['DestDir']):
destdir = hq[0]['DestDir']
logger.fdebug('location found @ %s' % destdir)
elif all(['COPY' in hq[0]['Status'], int(hq[0]['FileSizeMB']) > 0, hq[0]['DeleteStatus'] == 'COPY']):
config = self.server.config()
cDestDir = None
for x in config:
if x['Name'] == 'TempDir':
cTempDir = x['Value']
elif x['Name'] == 'DestDir':
cDestDir = x['Value']
if cDestDir is not None:
break
if cTempDir in hq[0]['DestDir']:
destdir2 = re.sub(cTempDir, cDestDir, hq[0]['DestDir']).strip()
if not destdir2.endswith(os.sep):
destdir2 = destdir2 + os.sep
destdir = os.path.join(destdir2, hq[0]['Name'])
logger.fdebug('NZBGET Destination dir set to: %s' % destdir)
else:
logger.warn('no file found where it should be @ %s - is there another script that moves things after completion ?' % hq[0]['DestDir'])
return {'status': 'file not found', 'failed': False}
if mylar.CONFIG.NZBGET_DIRECTORY is not None:
destdir2 = mylar.CONFIG.NZBGET_DIRECTORY
if not destdir2.endswith(os.sep):
destdir = destdir2 + os.sep
destdir = os.path.join(destdir2, hq[0]['Name'])
logger.fdebug('NZBGet Destination folder set via config to: %s' % destdir)
if destdir is not None:
return {'status': True,
'name': re.sub('.nzb', '', hq[0]['Name']).strip(),
'location': destdir,
'failed': False,
'issueid': nzbinfo['issueid'],
'comicid': nzbinfo['comicid'],
'apicall': True,
'ddl': False}
else:
logger.warn('Could not find completed NZBID %s in history' % nzbid)
return {'status': False}
| 11,264 | Python | .py | 213 | 37.596244 | 182 | 0.529241 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,245 | api.py | evilhero_mylar/mylar/api.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import mylar
from mylar import db, mb, importer, search, process, versioncheck, logger, webserve, helpers, encrypted
import simplejson as simplejson
import json
import cherrypy
import random
import os
import urllib2
import cache
import imghdr
from operator import itemgetter
from cherrypy.lib.static import serve_file, serve_download
import datetime
cmd_list = ['getIndex', 'getComic', 'getUpcoming', 'getWanted', 'getHistory',
'getLogs', 'getAPI', 'clearLogs','findComic', 'addComic', 'delComic',
'pauseComic', 'resumeComic', 'refreshComic', 'addIssue',
'queueIssue', 'unqueueIssue', 'forceSearch', 'forceProcess',
'getVersion', 'checkGithub','shutdown', 'restart', 'update',
'getComicInfo', 'getIssueInfo', 'getArt', 'downloadIssue',
'downloadNZB', 'getReadList', 'getStoryArc', 'addStoryArc']
class Api(object):
API_ERROR_CODE_DEFAULT = 460
def __init__(self):
self.apikey = None
self.cmd = None
self.id = None
self.img = None
self.file = None
self.filename = None
self.kwargs = None
self.data = None
self.callback = None
self.apitype = None
self.comicrn = False
def _failureResponse(self, errorMessage, code = API_ERROR_CODE_DEFAULT):
response = {
'success': False,
'error': {
'code': code,
'message': errorMessage
}
}
cherrypy.response.headers['Content-Type'] = "application/json"
return simplejson.dumps(response)
def _successResponse(self, results):
response = {
'success': True,
'data': results
}
cherrypy.response.headers['Content-Type'] = "application/json"
return simplejson.dumps(response)
def _resultsFromQuery(self, query):
myDB = db.DBConnection()
rows = myDB.select(query)
results = []
for row in rows:
results.append(dict(zip(row.keys(), row)))
return results
def checkParams(self, *args, **kwargs):
if 'cmd' not in kwargs:
self.data = self._failureResponse('Missing parameter: cmd')
return
if 'apikey' not in kwargs and ('apikey' not in kwargs and kwargs['cmd'] != 'getAPI'):
self.data = self._failureResponse('Missing API key')
return
elif kwargs['cmd'] == 'getAPI':
self.apitype = 'normal'
else:
if not mylar.CONFIG.API_ENABLED:
if kwargs['apikey'] != mylar.DOWNLOAD_APIKEY:
self.data = self._failureResponse('API not enabled')
return
if kwargs['apikey'] != mylar.CONFIG.API_KEY and all([kwargs['apikey'] != mylar.DOWNLOAD_APIKEY, mylar.DOWNLOAD_APIKEY != None]):
self.data = self._failureResponse('Incorrect API key')
return
else:
if kwargs['apikey'] == mylar.CONFIG.API_KEY:
self.apitype = 'normal'
elif kwargs['apikey'] == mylar.DOWNLOAD_APIKEY:
self.apitype = 'download'
logger.fdebug('Matched to key. Api set to : ' + self.apitype + ' mode.')
self.apikey = kwargs.pop('apikey')
if not([mylar.CONFIG.API_KEY, mylar.DOWNLOAD_APIKEY]):
self.data = self._failureResponse('API key not generated')
return
if self.apitype:
if self.apitype == 'normal' and len(mylar.CONFIG.API_KEY) != 32:
self.data = self._failureResponse('API key not generated correctly')
return
if self.apitype == 'download' and len(mylar.DOWNLOAD_APIKEY) != 32:
self.data = self._failureResponse('Download API key not generated correctly')
return
else:
self.data = self._failureResponse('API key not generated correctly')
return
if kwargs['cmd'] not in cmd_list:
self.data = self._failureResponse('Unknown command: %s' % kwargs['cmd'])
return
else:
self.cmd = kwargs.pop('cmd')
self.kwargs = kwargs
self.data = 'OK'
def fetchData(self):
if self.data == 'OK':
logger.fdebug('Received API command: ' + self.cmd)
methodToCall = getattr(self, "_" + self.cmd)
result = methodToCall(**self.kwargs)
if 'callback' not in self.kwargs:
if self.img:
return serve_file(path=self.img, content_type='image/jpeg')
if self.file and self.filename:
return serve_download(path=self.file, name=self.filename)
if isinstance(self.data, basestring):
return self.data
else:
if self.comicrn is True:
return self.data
else:
cherrypy.response.headers['Content-Type'] = "application/json"
return simplejson.dumps(self.data)
else:
self.callback = self.kwargs['callback']
self.data = simplejson.dumps(self.data)
self.data = self.callback + '(' + self.data + ');'
cherrypy.response.headers['Content-Type'] = "application/javascript"
return self.data
else:
return self.data
def _selectForComics(self):
return 'SELECT \
ComicID as id,\
ComicName as name,\
ComicImageURL as imageURL,\
Status as status,\
ComicPublisher as publisher,\
ComicYear as year,\
LatestIssue as latestIssue,\
Total as totalIssues,\
DetailURL as detailsURL\
FROM comics'
def _selectForIssues(self):
return 'SELECT \
IssueID as id,\
IssueName as name,\
ImageURL as imageURL,\
Issue_Number as number,\
ReleaseDate as releaseDate,\
IssueDate as issueDate,\
Status as status,\
ComicName as comicName\
FROM issues'
def _selectForAnnuals(self):
return 'SELECT \
IssueID as id,\
IssueName as name,\
Issue_Number as number,\
ReleaseDate as releaseDate,\
IssueDate as issueDate,\
Status as status,\
ComicName as comicName\
FROM annuals'
def _selectForReadList(self):
return 'SELECT \
IssueID as id,\
Issue_Number as number,\
IssueDate as issueDate,\
Status as status,\
ComicName as comicName\
FROM readlist'
def _getAPI(self, **kwargs):
if 'username' not in kwargs:
self.data = self._failureResponse('Missing parameter: username')
return
else:
username = kwargs['username']
if 'password' not in kwargs:
self.data = self._failureResponse('Missing parameter: password')
return
else:
password = kwargs['password']
if any([mylar.CONFIG.HTTP_USERNAME is None, mylar.CONFIG.HTTP_PASSWORD is None]):
self.data = self._failureResponse('Unable to use this command - username & password MUST be enabled.')
return
ht_user = mylar.CONFIG.HTTP_USERNAME
edc = encrypted.Encryptor(mylar.CONFIG.HTTP_PASSWORD)
ed_chk = edc.decrypt_it()
if mylar.CONFIG.ENCRYPT_PASSWORDS is True:
if username == ht_user and all([ed_chk['status'] is True, ed_chk['password'] == password]):
self.data = self._successResponse(
{'apikey': mylar.CONFIG.API_KEY}
)
else:
self.data = self._failureResponse('Incorrect username or password.')
else:
if username == ht_user and password == mylar.CONFIG.HTTP_PASSWORD:
self.data = self._successResponse(
{'apikey': mylar.CONFIG.API_KEY}
)
else:
self.data = self._failureResponse('Incorrect username or password.')
def _getIndex(self, **kwargs):
query = '{select} ORDER BY ComicSortName COLLATE NOCASE'.format(
select = self._selectForComics()
)
self.data = self._successResponse(
self._resultsFromQuery(query)
)
return
def _getReadList(self, **kwargs):
readListQuery = '{select} ORDER BY IssueDate ASC'.format(
select = self._selectForReadList()
)
self.data = self._successResponse(
self._resultsFromQuery(readListQuery)
)
return
def _getComic(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
comicQuery = '{select} WHERE ComicID="{id}" ORDER BY ComicSortName COLLATE NOCASE'.format(
select = self._selectForComics(),
id = self.id
)
comic = self._resultsFromQuery(comicQuery)
issuesQuery = '{select} WHERE ComicID="{id}" ORDER BY Int_IssueNumber DESC'.format(
select = self._selectForIssues(),
id = self.id
)
issues = self._resultsFromQuery(issuesQuery)
if mylar.CONFIG.ANNUALS_ON:
annualsQuery = '{select} WHERE ComicID="{id}"'.format(
select = self._selectForAnnuals(),
id = self.id
)
annuals = self._resultsFromQuery(annualsQuery)
else:
annuals = []
self.data = self._successResponse({
'comic': comic,
'issues': issues,
'annuals': annuals
})
return
def _getHistory(self, **kwargs):
self.data = self._successResponse(
self._resultsFromQuery('SELECT * from snatched order by DateAdded DESC')
)
return
def _getUpcoming(self, **kwargs):
if 'include_downloaded_issues' in kwargs and kwargs['include_downloaded_issues'].upper() == 'Y':
select_status_clause = "w.STATUS IN ('Wanted', 'Snatched', 'Downloaded')"
else:
select_status_clause = "w.STATUS = 'Wanted'"
# Days in a new year that precede the first Sunday will look to the previous Sunday for week and year.
today = datetime.date.today()
if today.strftime('%U') == '00':
weekday = 0 if today.isoweekday() == 7 else today.isoweekday()
sunday = today - datetime.timedelta(days=weekday)
week = sunday.strftime('%U')
year = sunday.strftime('%Y')
else:
week = today.strftime('%U')
year = today.strftime('%Y')
self.data = self._resultsFromQuery(
"SELECT w.COMIC AS ComicName, w.ISSUE AS IssueNumber, w.ComicID, w.IssueID, w.SHIPDATE AS IssueDate, w.STATUS AS Status, c.ComicName AS DisplayComicName \
FROM weekly w JOIN comics c ON w.ComicID = c.ComicID WHERE w.COMIC IS NOT NULL AND w.ISSUE IS NOT NULL AND \
SUBSTR('0' || w.weeknumber, -2) = '" + week + "' AND w.year = '" + year + "' AND " + select_status_clause + " ORDER BY c.ComicSortName")
return
def _getWanted(self, **kwargs):
self.data = self._resultsFromQuery("SELECT * from issues WHERE Status='Wanted'")
return
def _getLogs(self, **kwargs):
self.data = mylar.LOG_LIST
return
def _clearLogs(self, **kwargs):
mylar.LOG_LIST = []
self.data = 'Cleared log'
return
def _delComic(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
myDB = db.DBConnection()
myDB.action('DELETE from comics WHERE ComicID="' + self.id + '"')
myDB.action('DELETE from issues WHERE ComicID="' + self.id + '"')
myDB.action('DELETE from upcoming WHERE ComicID="' + self.id + '"')
def _pauseComic(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
myDB = db.DBConnection()
controlValueDict = {'ComicID': self.id}
newValueDict = {'Status': 'Paused'}
myDB.upsert("comics", newValueDict, controlValueDict)
def _resumeComic(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
myDB = db.DBConnection()
controlValueDict = {'ComicID': self.id}
newValueDict = {'Status': 'Active'}
myDB.upsert("comics", newValueDict, controlValueDict)
def _refreshComic(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
try:
importer.addComictoDB(self.id)
except Exception, e:
self.data = e
return
def _addComic(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
try:
importer.addComictoDB(self.id)
except Exception, e:
self.data = e
return
def _queueIssue(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
myDB = db.DBConnection()
controlValueDict = {'IssueID': self.id}
newValueDict = {'Status': 'Wanted'}
myDB.upsert("issues", newValueDict, controlValueDict)
search.searchforissue(self.id)
def _unqueueIssue(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
myDB = db.DBConnection()
controlValueDict = {'IssueID': self.id}
newValueDict = {'Status': 'Skipped'}
myDB.upsert("issues", newValueDict, controlValueDict)
def _forceSearch(self, **kwargs):
search.searchforissue()
def _issueProcess(self, **kwargs):
if 'comicid' not in kwargs:
self.data = self._failureResponse('Missing parameter: comicid')
return
else:
self.comicid = kwargs['comicid']
if 'issueid' not in kwargs:
self.issueid = None
else:
self.issueid = kwargs['issueid']
if 'folder' not in kwargs:
self.data = self._failureResponse('Missing parameter: folder')
return
else:
self.folder = kwargs['folder']
fp = process.Process(self.comicid, self.folder, self.issueid)
self.data = fp.post_process()
return
def _forceProcess(self, **kwargs):
if 'nzb_name' not in kwargs:
self.data = self._failureResponse('Missing parameter: nzb_name')
return
else:
self.nzb_name = kwargs['nzb_name']
if 'nzb_folder' not in kwargs:
self.data = self._failureResponse('Missing parameter: nzb_folder')
return
else:
self.nzb_folder = kwargs['nzb_folder']
if 'failed' not in kwargs:
failed = False
else:
failed = kwargs['failed']
if 'issueid' not in kwargs:
issueid = None
else:
issueid = kwargs['issueid']
if 'comicid' not in kwargs:
comicid = None
else:
comicid = kwargs['comicid']
if 'ddl' not in kwargs:
ddl = False
else:
ddl = True
if 'apc_version' not in kwargs:
logger.info('Received API Request for PostProcessing %s [%s]. Queueing...' % (self.nzb_name, self.nzb_folder))
mylar.PP_QUEUE.put({'nzb_name': self.nzb_name,
'nzb_folder': self.nzb_folder,
'issueid': issueid,
'failed': failed,
'comicid': comicid,
'apicall': True,
'ddl': ddl})
self.data = 'Successfully submitted request for post-processing for %s' % self.nzb_name
#fp = process.Process(self.nzb_name, self.nzb_folder, issueid=issueid, failed=failed, comicid=comicid, apicall=True)
#self.data = fp.post_process()
else:
logger.info('[API] Api Call from ComicRN detected - initiating script post-processing.')
fp = webserve.WebInterface()
self.data = fp.post_process(self.nzb_name, self.nzb_folder, failed=failed, apc_version=kwargs['apc_version'], comicrn_version=kwargs['comicrn_version'])
self.comicrn = True
return
def _getVersion(self, **kwargs):
self.data = self._successResponse({
'git_path': mylar.CONFIG.GIT_PATH,
'install_type': mylar.INSTALL_TYPE,
'current_version': mylar.CURRENT_VERSION,
'latest_version': mylar.LATEST_VERSION,
'commits_behind': mylar.COMMITS_BEHIND,
})
def _checkGithub(self, **kwargs):
versioncheck.checkGithub()
self._getVersion()
def _shutdown(self, **kwargs):
mylar.SIGNAL = 'shutdown'
def _restart(self, **kwargs):
mylar.SIGNAL = 'restart'
def _update(self, **kwargs):
mylar.SIGNAL = 'update'
def _getArtistArt(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
self.data = cache.getArtwork(ComicID=self.id)
def _getIssueArt(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
self.data = cache.getArtwork(IssueID=self.id)
def _getComicInfo(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
self.data = cache.getInfo(ComicID=self.id)
def _getIssueInfo(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
self.data = cache.getInfo(IssueID=self.id)
def _getArt(self, **kwargs):
if 'id' not in kwargs:
self.data = self._failureResponse('Missing parameter: id')
return
else:
self.id = kwargs['id']
img = None
image_path = os.path.join(mylar.CONFIG.CACHE_DIR, str(self.id) + '.jpg')
# Checks if its a valid path and file
if os.path.isfile(image_path):
# check if its a valid img
if imghdr.what(image_path):
self.img = image_path
return
else:
# If we cant find the image, lets check the db for a url.
comic = self._resultsFromQuery('SELECT * from comics WHERE ComicID="' + self.id + '"')
# Try every img url in the db
try:
img = urllib2.urlopen(comic[0]['ComicImageURL']).read()
except:
try:
img = urllib2.urlopen(comic[0]['ComicImageALTURL']).read()
except:
pass
if img:
# verify the img stream
if imghdr.what(None, img):
with open(image_path, 'wb') as f:
f.write(img)
self.img = image_path
return
else:
self.data = self._failureResponse('Failed return a image')
else:
self.data = self._failureResponse('Failed to return a image')
def _findComic(self, name, issue=None, type_=None, mode=None, explisit=None, serinfo=None):
# set defaults
if type_ is None:
type_ = 'comic'
if mode is None:
mode = 'series'
# Dont do shit if name is missing
if len(name) == 0:
self.data = self._failureResponse('Missing a Comic name')
return
if type_ == 'comic' and mode == 'series':
searchresults, explisit = mb.findComic(name, mode, issue=issue)
elif type_ == 'comic' and mode == 'pullseries':
pass
elif type_ == 'comic' and mode == 'want':
searchresults, explisit = mb.findComic(name, mode, issue)
elif type_ == 'story_arc':
searchresults, explisit = mb.findComic(name, mode, issue=None, explisit='explisit', type='story_arc')
searchresults = sorted(searchresults, key=itemgetter('comicyear', 'issues'), reverse=True)
self.data = searchresults
def _downloadIssue(self, id):
if not id:
self.data = self._failureResponse('You need to provide a issueid')
return
self.id = id
# Fetch a list of dicts from issues table
i = self._resultsFromQuery('SELECT * from issues WHERE issueID="' + self.id + '"')
if not len(i):
self.data = self._failureResponse('Couldnt find a issue with issueID %s' % self.id)
return
# issueid is unique so it should one dict in the list
issue = i[0]
issuelocation = issue.get('Location', None)
# Check the issue is downloaded
if issuelocation is not None:
# Find the comic location
comic = self._resultsFromQuery('SELECT * from comics WHERE comicID="' + issue['ComicID'] + '"')[0]
comiclocation = comic.get('ComicLocation')
f = os.path.join(comiclocation, issuelocation)
if not os.path.isfile(f):
if mylar.CONFIG.MULTIPLE_DEST_DIRS is not None and mylar.CONFIG.MULTIPLE_DEST_DIRS != 'None':
pathdir = os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(comiclocation))
f = os.path.join(pathdir, issuelocation)
self.file = f
self.filename = issuelocation
else:
self.file = f
self.filename = issuelocation
else:
self.data = self._failureResponse('You need to download that issue first')
return
def _downloadNZB(self, nzbname):
if not nzbname:
self.data = self._failureResponse('You need to provide a nzbname')
return
self.nzbname = nzbname
f = os.path.join(mylar.CONFIG.CACHE_DIR, nzbname)
if os.path.isfile(f):
self.file = f
self.filename = nzbname
else:
self.data = self._failureResponse('NZBname does not exist within the cache directory. Unable to retrieve.')
return
def _getStoryArc(self, **kwargs):
if not 'id' in kwargs:
if 'customOnly' in kwargs and kwargs['customOnly']:
self.data = self._resultsFromQuery('SELECT StoryArcID, StoryArc, MAX(ReadingOrder) AS HighestOrder from storyarcs WHERE StoryArcID LIKE "C%" GROUP BY StoryArcID ORDER BY StoryArc')
else:
self.data = self._resultsFromQuery('SELECT StoryArcID, StoryArc, MAX(ReadingOrder) AS HighestOrder from storyarcs GROUP BY StoryArcID ORDER BY StoryArc')
else:
self.id = kwargs['id']
self.data = self._resultsFromQuery('SELECT StoryArc, ReadingOrder, ComicID, ComicName, IssueNumber, IssueID, \
IssueDate, IssueName, IssuePublisher from storyarcs WHERE StoryArcID="' + self.id + '" ORDER BY ReadingOrder')
return
def _addStoryArc(self, **kwargs):
issuecount = 0
if not 'id' in kwargs:
self.id = 'C%04d' % random.randint(1, 9999)
if not 'storyarcname' in kwargs:
self.data = self._failureResponse('You need to provide either id or storyarcname')
return
else:
storyarcname = kwargs.pop('storyarcname')
else:
self.id = kwargs.pop('id')
arc = self._resultsFromQuery('SELECT * from storyarcs WHERE StoryArcID="' + self.id + '" ORDER by ReadingOrder')
storyarcname = arc[0]['StoryArc']
issuecount = len(arc)
if not 'issues' in kwargs and not 'arclist' in kwargs:
self.data = self._failureResponse('No issues specified')
return
else:
arclist = ""
if 'issues' in kwargs:
issuelist = kwargs.pop('issues').split(",")
index = 0
for issue in issuelist:
arclist += "%s,%s" % (issue, issuecount + 1)
index += 1
issuecount += 1
if index < len(issuelist):
arclist += "|"
if 'arclist' in kwargs:
cvlist = kwargs.pop('arclist')
issuelist = cvlist.split("|")
index = 0
for issue in issuelist:
arclist += "%s,%s" % (issue.split(",")[0],issuecount + 1)
index += 1
issuecount += 1
if index < len(issuelist):
arclist += "|"
wi = webserve.WebInterface()
logger.info("arclist: %s - arcid: %s - storyarcname: %s - storyarcissues: %s" % (arclist, self.id, storyarcname, issuecount))
wi.addStoryArc_thread(arcid=self.id, storyarcname=storyarcname, storyarcissues=issuecount, arclist=arclist, **kwargs)
return
class REST(object):
def __init__(self):
pass
class verify_api(object):
def __init__(self):
pass
def validate(self):
logger.info('attempting to validate...')
req = cherrypy.request.headers
logger.info('thekey: %s' % req)
logger.info('url: %s' % cherrypy.url())
logger.info('mylar.apikey: %s [%s]' % (mylar.CONFIG.API_KEY, type(mylar.CONFIG.API_KEY)))
logger.info('submitted.apikey: %s [%s]' % (req['Api-Key'], type(req['Api-Key'])))
if 'Api-Key' not in req or req['Api-Key'] != str(mylar.CONFIG.API_KEY): #str(mylar.API_KEY) or mylar.API_KEY not in cherrypy.url():
logger.info('wrong APIKEY')
return 'api-key provided was either not present in auth header, or was incorrect.'
else:
return True
class Watchlist(object):
exposed = True
def __init__(self):
pass
def GET(self):
va = REST.verify_api()
vchk = va.validate()
if vchk is not True:
return('api-key provided was either not present in auth header, or was incorrect.')
#rows_as_dic = []
#for row in rows:
# row_as_dic = dict(zip(row.keys(), row))
# rows_as_dic.append(row_as_dic)
#return rows_as_dic
some = helpers.havetotals()
return simplejson.dumps(some)
class Comics(object):
exposed = True
def __init__(self):
pass
def _dic_from_query(self, query):
myDB = db.DBConnection()
rows = myDB.select(query)
rows_as_dic = []
for row in rows:
row_as_dic = dict(zip(row.keys(), row))
rows_as_dic.append(row_as_dic)
return rows_as_dic
def GET(self):
va = REST.verify_api()
vchk = va.validate()
if vchk is not True:
return('api-key provided was either not present in auth header, or was incorrect.')
#req = cherrypy.request.headers
#logger.info('thekey: %s' % req)
#if 'api-key' not in req or req['api-key'] != 'hello':
# logger.info('wrong APIKEY')
# return('api-key provided was either not present in auth header, or was incorrect.')
self.comics = self._dic_from_query('SELECT * from comics order by ComicSortName COLLATE NOCASE')
return('Here are all the comics we have: %s' % self.comics)
@cherrypy.popargs('comic_id','issuemode','issue_id')
class Comic(object):
exposed = True
def __init__(self):
pass
def _dic_from_query(self, query):
myDB = db.DBConnection()
rows = myDB.select(query)
rows_as_dic = []
for row in rows:
row_as_dic = dict(zip(row.keys(), row))
rows_as_dic.append(row_as_dic)
return rows_as_dic
def GET(self, comic_id=None, issuemode=None, issue_id=None):
va = REST.verify_api()
vchk = va.validate()
if vchk is not True:
return('api-key provided was either not present in auth header, or was incorrect.')
#req = cherrypy.request.headers
#logger.info('thekey: %s' % req)
#if 'api-key' not in req or req['api-key'] != 'hello':
# logger.info('wrong APIKEY')
# return('api-key provided was either not present in auth header, or was incorrect.')
self.comics = self._dic_from_query('SELECT * from comics order by ComicSortName COLLATE NOCASE')
if comic_id is None:
return('No valid ComicID entered')
else:
if issuemode is None:
match = [c for c in self.comics if comic_id == c['ComicID']]
if match:
return json.dumps(match,ensure_ascii=False)
else:
return('No Comic with the ID %s :-(' % comic_id)
elif issuemode == 'issues':
self.issues = self._dic_from_query('SELECT * from issues where comicid="' + comic_id + '"')
return json.dumps(self.issues, ensure_ascii=False)
elif issuemode == 'issue' and issue_id is not None:
self.issues = self._dic_from_query('SELECT * from issues where comicid="' + comic_id + '" and issueid="' + issue_id + '"')
return json.dumps(self.issues, ensure_ascii=False)
else:
return('Nothing to do.')
| 31,970 | Python | .py | 731 | 31.722298 | 196 | 0.560097 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,246 | utorrent.py | evilhero_mylar/mylar/utorrent.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import re
import os
import requests
import bencode
import hashlib
import StringIO
import mylar
from mylar import logger
class utorrentclient(object):
def __init__(self):
host = mylar.CONFIG.UTORRENT_HOST #has to be in the format of URL:PORT
if not host.startswith('http'):
host = 'http://' + host
if host.endswith('/'):
host = host[:-1]
if host.endswith('/gui'):
host = host[:-4]
self.base_url = host
self.username = mylar.CONFIG.UTORRENT_USERNAME
self.password = mylar.CONFIG.UTORRENT_PASSWORD
self.utorrent_url = '%s/gui/' % (self.base_url)
self.auth = requests.auth.HTTPBasicAuth(self.username, self.password)
self.token, self.cookies = self._get_token()
def _get_token(self):
TOKEN_REGEX = r'<div[^>]*id=[\"\']token[\"\'][^>]*>([^<]*)</div>'
utorrent_url_token = '%stoken.html' % self.utorrent_url
try:
r = requests.get(utorrent_url_token, auth=self.auth)
except requests.exceptions.RequestException as err:
logger.debug('URL: ' + str(utorrent_url_token))
logger.debug('Error getting Token. uTorrent responded with error: ' + str(err))
return 'fail'
token = re.search(TOKEN_REGEX, r.text).group(1)
guid = r.cookies['GUID']
cookies = dict(GUID = guid)
return token, cookies
def addfile(self, filepath=None, filename=None, bytes=None):
params = {'action': 'add-file', 'token': self.token}
try:
d = open(filepath, 'rb')
tordata = d.read()
d.close()
except:
logger.warn('Unable to load torrent file. Aborting at this time.')
return 'fail'
files = {'torrent_file': tordata}
try:
r = requests.post(url=self.utorrent_url, auth=self.auth, cookies=self.cookies, params=params, files=files)
except requests.exceptions.RequestException as err:
logger.debug('URL: ' + str(self.utorrent_url))
logger.debug('Error sending to uTorrent Client. uTorrent responded with error: ' + str(err))
return 'fail'
# (to-do) verify the hash in order to ensure it's loaded here
if str(r.status_code) == '200':
logger.info('Successfully added torrent to uTorrent client.')
hash = self.calculate_torrent_hash(data=tordata)
if mylar.CONFIG.UTORRENT_LABEL:
try:
self.setlabel(hash)
except:
logger.warn('Unable to set label for torrent.')
return hash
else:
return 'fail'
def addurl(self, url):
params = {'action': 'add-url', 'token': self.token, 's': url}
try:
r = requests.post(url=self.utorrent_url, auth=self.auth, cookies=self.cookies, params=params)
except requests.exceptions.RequestException as err:
logger.debug('URL: ' + str(self.utorrent_url))
logger.debug('Error sending to uTorrent Client. uTorrent responded with error: ' + str(err))
return 'fail'
# (to-do) verify the hash in order to ensure it's loaded here
if str(r.status_code) == '200':
logger.info('Successfully added torrent to uTorrent client.')
hash = self.calculate_torrent_hash(link=url)
if mylar.CONFIG.UTORRENT_LABEL:
try:
self.setlabel(hash)
except:
logger.warn('Unable to set label for torrent.')
return hash
else:
return 'fail'
def setlabel(self, hash):
params = {'token': self.token, 'action': 'setprops', 'hash': hash, 's': 'label', 'v': str(mylar.CONFIG.UTORRENT_LABEL)}
r = requests.post(url=self.utorrent_url, auth=self.auth, cookies=self.cookies, params=params)
if str(r.status_code) == '200':
logger.info('label ' + str(mylar.CONFIG.UTORRENT_LABEL) + ' successfully applied')
else:
logger.info('Unable to label torrent')
return
def calculate_torrent_hash(self, link=None, filepath=None, data=None):
thehash = None
if link is None:
if filepath:
torrent_file = open(filepath, "rb")
metainfo = bencode.decode(torrent_file.read())
else:
metainfo = bencode.decode(data)
info = metainfo['info']
thehash = hashlib.sha1(bencode.encode(info)).hexdigest().upper()
logger.info('Hash: ' + thehash)
else:
if link.startswith("magnet:"):
torrent_hash = re.findall("urn:btih:([\w]{32,40})", link)[0]
if len(torrent_hash) == 32:
torrent_hash = b16encode(b32decode(torrent_hash)).lower()
thehash = torrent_hash.upper()
if thehash is None:
logger.warn('Cannot calculate torrent hash without magnet link or data')
return thehash
# not implemented yet #
# def load_torrent(self, filepath):
# start = bool(mylar.CONFIG.UTORRENT_STARTONLOAD)
# logger.info('filepath to torrent file set to : ' + filepath)
#
# torrent = self.addfile(filepath, verify_load=True)
#torrent should return the hash if it's valid and loaded (verify_load checks)
# if not torrent:
# return False
# if mylar.CONFIG.UTORRENT_LABEL:
# self.setlabel(torrent)
# logger.info('Setting label for torrent to : ' + mylar.CONFIG.UTORRENT_LABEL)
# logger.info('Successfully loaded torrent.')
# #note that if set_directory is enabled, the torrent has to be started AFTER it's loaded or else it will give chunk errors and not seed
# if start:
# logger.info('[' + str(start) + '] Now starting torrent.')
# torrent.start()
# else:
# logger.info('[' + str(start) + '] Not starting torrent due to configuration setting.')
# return True
| 6,754 | Python | .py | 146 | 37.513699 | 143 | 0.608782 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,247 | process.py | evilhero_mylar/mylar/process.py | # This file is part of Mylar.
# -*- coding: utf-8 -*-
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import Queue
import threading
import mylar
import logger
class Process(object):
def __init__(self, nzb_name, nzb_folder, failed=False, issueid=None, comicid=None, apicall=False, ddl=False):
self.nzb_name = nzb_name
self.nzb_folder = nzb_folder
self.failed = failed
self.issueid = issueid
self.comicid = comicid
self.apicall = apicall
self.ddl = ddl
def post_process(self):
if self.failed == '0':
self.failed = False
elif self.failed == '1':
self.failed = True
queue = Queue.Queue()
retry_outside = False
if self.failed is False:
PostProcess = mylar.PostProcessor.PostProcessor(self.nzb_name, self.nzb_folder, self.issueid, queue=queue, comicid=self.comicid, apicall=self.apicall, ddl=self.ddl)
if any([self.nzb_name == 'Manual Run', self.nzb_name == 'Manual+Run', self.apicall is True, self.issueid is not None]):
threading.Thread(target=PostProcess.Process).start()
else:
thread_ = threading.Thread(target=PostProcess.Process, name="Post-Processing")
thread_.start()
thread_.join()
chk = queue.get()
while True:
if chk[0]['mode'] == 'fail':
logger.info('Initiating Failed Download handling')
if chk[0]['annchk'] == 'no':
mode = 'want'
else:
mode = 'want_ann'
self.failed = True
break
elif chk[0]['mode'] == 'stop':
break
elif chk[0]['mode'] == 'outside':
retry_outside = True
break
else:
logger.error('mode is unsupported: ' + chk[0]['mode'])
break
if self.failed is True:
if mylar.CONFIG.FAILED_DOWNLOAD_HANDLING is True:
#drop the if-else continuation so we can drop down to this from the above if statement.
logger.info('Initiating Failed Download handling for this download.')
FailProcess = mylar.Failed.FailedProcessor(nzb_name=self.nzb_name, nzb_folder=self.nzb_folder, queue=queue)
thread_ = threading.Thread(target=FailProcess.Process, name="FAILED Post-Processing")
thread_.start()
thread_.join()
failchk = queue.get()
if failchk[0]['mode'] == 'retry':
logger.info('Attempting to return to search module with ' + str(failchk[0]['issueid']))
if failchk[0]['annchk'] == 'no':
mode = 'want'
else:
mode = 'want_ann'
qq = mylar.webserve.WebInterface()
qt = qq.queueit(mode=mode, ComicName=failchk[0]['comicname'], ComicIssue=failchk[0]['issuenumber'], ComicID=failchk[0]['comicid'], IssueID=failchk[0]['issueid'], manualsearch=True)
elif failchk[0]['mode'] == 'stop':
pass
else:
logger.error('mode is unsupported: ' + failchk[0]['mode'])
else:
logger.warn('Failed Download Handling is not enabled. Leaving Failed Download as-is.')
if retry_outside:
PostProcess = mylar.PostProcessor.PostProcessor('Manual Run', self.nzb_folder, queue=queue)
thread_ = threading.Thread(target=PostProcess.Process, name="Post-Processing")
thread_.start()
thread_.join()
chk = queue.get()
while True:
if chk[0]['mode'] == 'fail':
logger.info('Initiating Failed Download handling')
if chk[0]['annchk'] == 'no':
mode = 'want'
else:
mode = 'want_ann'
self.failed = True
break
elif chk[0]['mode'] == 'stop':
break
else:
logger.error('mode is unsupported: ' + chk[0]['mode'])
break
return
| 5,033 | Python | .py | 105 | 33.752381 | 200 | 0.539837 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,248 | readinglist.py | evilhero_mylar/mylar/readinglist.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import os
import re
import mylar
from mylar import logger, db, helpers
class Readinglist(object):
def __init__(self, filelist=None, IssueID=None, IssueArcID=None):
if IssueID:
self.IssueID = IssueID
else:
self.IssueID = None
if IssueArcID:
self.IssueArcID = IssueArcID
else:
self.IssueArcID = None
if filelist:
self.filelist = filelist
else:
self.filelist = None
self.module = '[READLIST]'
def addtoreadlist(self):
annualize = False
myDB = db.DBConnection()
readlist = myDB.selectone("SELECT * from issues where IssueID=?", [self.IssueID]).fetchone()
if readlist is None:
logger.fdebug(self.module + ' Checking against annuals..')
readlist = myDB.selectone("SELECT * from annuals where IssueID=?", [self.IssueID]).fetchone()
if readlist is None:
logger.error(self.module + ' Cannot locate IssueID - aborting..')
return
else:
logger.fdebug('%s Successfully found annual for %s' % (self.module, readlist['ComicID']))
annualize = True
comicinfo = myDB.selectone("SELECT * from comics where ComicID=?", [readlist['ComicID']]).fetchone()
logger.info(self.module + ' Attempting to add issueid ' + readlist['IssueID'])
if comicinfo is None:
logger.info(self.module + ' Issue not located on your current watchlist. I should probably check story-arcs but I do not have that capability just yet.')
else:
locpath = None
if mylar.CONFIG.MULTIPLE_DEST_DIRS is not None and mylar.CONFIG.MULTIPLE_DEST_DIRS != 'None' and os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(comicinfo['ComicLocation'])) != comicinfo['ComicLocation']:
pathdir = os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(comicinfo['ComicLocation']))
if os.path.exists(os.path.join(pathdir, readlist['Location'])):
locpath = os.path.join(pathdir, readlist['Location'])
else:
if os.path.exists(os.path.join(comicinfo['ComicLocation'], readlist['Location'])):
locpath = os.path.join(comicinfo['ComicLocation'], readlist['Location'])
else:
if os.path.exists(os.path.join(comicinfo['ComicLocation'], readlist['Location'])):
locpath = os.path.join(comicinfo['ComicLocation'], readlist['Location'])
if not locpath is None:
comicissue = readlist['Issue_Number']
if annualize is True:
comicname = readlist['ReleaseComicName']
else:
comicname = comicinfo['ComicName']
dspinfo = comicname + ' #' + comicissue
if annualize is True:
if mylar.CONFIG.ANNUALS_ON is True:
dspinfo = comicname + ' #' + readlist['Issue_Number']
if 'annual' in comicname.lower():
comicissue = 'Annual ' + readlist['Issue_Number']
elif 'special' in comicname.lower():
comicissue = 'Special ' + readlist['Issue_Number']
ctrlval = {"IssueID": self.IssueID}
newval = {"DateAdded": helpers.today(),
"Status": "Added",
"ComicID": readlist['ComicID'],
"Issue_Number": comicissue,
"IssueDate": readlist['IssueDate'],
"SeriesYear": comicinfo['ComicYear'],
"ComicName": comicname,
"Location": locpath}
myDB.upsert("readlist", newval, ctrlval)
logger.info(self.module + ' Added ' + dspinfo + ' to the Reading list.')
return
def markasRead(self):
myDB = db.DBConnection()
if self.IssueID:
issue = myDB.selectone('SELECT * from readlist WHERE IssueID=?', [self.IssueID]).fetchone()
if issue['Status'] == 'Read':
NewVal = {"Status": "Added"}
else:
NewVal = {"Status": "Read"}
NewVal['StatusChange'] = helpers.today()
CtrlVal = {"IssueID": self.IssueID}
myDB.upsert("readlist", NewVal, CtrlVal)
logger.info(self.module + ' Marked ' + issue['ComicName'] + ' #' + str(issue['Issue_Number']) + ' as Read.')
elif self.IssueArcID:
issue = myDB.selectone('SELECT * from readinglist WHERE IssueArcID=?', [self.IssueArcID]).fetchone()
if issue['Status'] == 'Read':
NewVal = {"Status": "Added"}
else:
NewVal = {"Status": "Read"}
NewVal['StatusChange'] = helpers.today()
CtrlVal = {"IssueArcID": self.IssueArcID}
myDB.upsert("readinglist", NewVal, CtrlVal)
logger.info(self.module + ' Marked ' + issue['ComicName'] + ' #' + str(issue['IssueNumber']) + ' as Read.')
return
def syncreading(self):
#3 status' exist for the readlist.
# Added (Not Read) - Issue is added to the readlist and is awaiting to be 'sent' to your reading client.
# Read - Issue has been read
# Not Read - Issue has been downloaded to your reading client after the syncfiles has taken place.
module = '[READLIST-TRANSFER]'
myDB = db.DBConnection()
readlist = []
cidlist = []
sendlist = []
if self.filelist is None:
rl = myDB.select('SELECT issues.IssueID, comics.ComicID, comics.ComicLocation, issues.Location FROM readlist LEFT JOIN issues ON issues.IssueID = readlist.IssueID LEFT JOIN comics on comics.ComicID = issues.ComicID WHERE readlist.Status="Added"')
if rl is None:
logger.info(module + ' No issues have been marked to be synced. Aborting syncfiles')
return
for rlist in rl:
readlist.append({"filepath": os.path.join(rlist['ComicLocation'],rlist['Location']),
"issueid": rlist['IssueID'],
"comicid": rlist['ComicID']})
else:
readlist = self.filelist
if len(readlist) > 0:
for clist in readlist:
if clist['filepath'] == 'None' or clist['filepath'] is None:
logger.warn(module + ' There was a problem with ComicID/IssueID: [' + clist['comicid'] + '/' + clist['issueid'] + ']. I cannot locate the file in the given location (try re-adding to your readlist)[' + clist['filepath'] + ']')
continue
else:
# multiplecid = False
# for x in cidlist:
# if clist['comicid'] == x['comicid']:
# comicid = x['comicid']
# comiclocation = x['location']
# multiplecid = True
# if multiplecid == False:
# cid = myDB.selectone("SELECT * FROM comics WHERE ComicID=?", [clist['comicid']]).fetchone()
# if cid is None:
# continue
# else:
# comiclocation = cid['ComicLocation']
# comicid = cid['ComicID']
# if mylar.CONFIG.MULTIPLE_DEST_DIRS is not None and mylar.CONFIG.MULTIPLE_DEST_DIRS != 'None' and os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(comiclocation)) != comiclocation:
# logger.fdebug(module + ' Multiple_dest_dirs:' + mylar.CONFIG.MULTIPLE_DEST_DIRS)
# logger.fdebug(module + ' Dir: ' + comiclocation)
# logger.fdebug(module + ' Os.path.basename: ' + os.path.basename(comiclocation))
# pathdir = os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(comiclocation))
if os.path.exists(clist['filepath']):
sendlist.append({"issueid": clist['issueid'],
"filepath": clist['filepath'],
"filename": os.path.split(clist['filepath'])[1]})
# else:
# if os.path.exists(os.path.join(comiclocation, clist['filename'])):
# sendlist.append({"issueid": clist['issueid'],
# "filepath": comiclocation,
# "filename": clist['filename']})
# else:
# if os.path.exists(os.path.join(comiclocation, clist['filename'])):
# sendlist.append({"issueid": clist['issueid'],
# "filepath": comiclocation,
# "filename": clist['filename']})
else:
logger.warn(module + ' ' + clist['filepath'] + ' does not exist in the given location. Remove from the Reading List and Re-add and/or confirm the file exists in the specified location')
continue
# #cidlist is just for this reference loop to not make unnecessary db calls if the comicid has already been processed.
# cidlist.append({"comicid": clist['comicid'],
# "issueid": clist['issueid'],
# "location": comiclocation}) #store the comicid so we don't make multiple sql requests
if len(sendlist) == 0:
logger.info(module + ' Nothing to send from your readlist')
return
logger.info(module + ' ' + str(len(sendlist)) + ' issues will be sent to your reading device.')
# test if IP is up.
import shlex
import subprocess
#fhost = mylar.CONFIG.TAB_HOST.find(':')
host = mylar.CONFIG.TAB_HOST[:mylar.CONFIG.TAB_HOST.find(':')]
if 'windows' not in mylar.OS_DETECT.lower():
cmdstring = str('ping -c1 ' + str(host))
else:
cmdstring = str('ping -n 1 ' + str(host))
cmd = shlex.split(cmdstring)
try:
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError, e:
logger.info(module + ' The host {0} is not Reachable at this time.'.format(cmd[-1]))
return
else:
if 'unreachable' in output:
logger.info(module + ' The host {0} is not Reachable at this time.'.format(cmd[-1]))
return
else:
logger.info(module + ' The host {0} is Reachable. Preparing to send files.'.format(cmd[-1]))
success = mylar.ftpsshup.sendfiles(sendlist)
if success == 'fail':
return
if len(success) > 0:
for succ in success:
newCTRL = {"issueid": succ['issueid']}
newVAL = {"Status": 'Downloaded',
"StatusChange": helpers.today()}
myDB.upsert("readlist", newVAL, newCTRL)
| 12,328 | Python | .py | 212 | 45.754717 | 258 | 0.537157 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,249 | auth.py | evilhero_mylar/mylar/auth.py | #!/usr/bin/env python
# -*- encoding: UTF-8 -*-
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
#
######
# Form based authentication for CherryPy. Requires the
# Session tool to be loaded.
###### from cherrypy/tools on github
import cherrypy
from cherrypy.lib.static import serve_file
from cgi import escape
#from datetime import datetime, timedelta
import urllib
import re
import mylar
from mylar import logger, encrypted
SESSION_KEY = '_cp_username'
def check_credentials(username, password):
"""Verifies credentials for username and password.
Returns None on success or a string describing the error on failure"""
# Adapt to your needs
forms_user = cherrypy.request.config['auth.forms_username']
forms_pass = cherrypy.request.config['auth.forms_password']
edc = encrypted.Encryptor(forms_pass)
ed_chk = edc.decrypt_it()
if mylar.CONFIG.ENCRYPT_PASSWORDS is True:
if username == forms_user and all([ed_chk['status'] is True, ed_chk['password'] == password]):
return None
else:
return u"Incorrect username or password."
else:
if username == forms_user and password == forms_pass:
return None
else:
return u"Incorrect username or password."
def check_auth(*args, **kwargs):
"""A tool that looks in config for 'auth.require'. If found and it
is not None, a login is required and the entry is evaluated as a list of
conditions that the user must fulfill"""
conditions = cherrypy.request.config.get('auth.require', None)
get_params = urllib.quote(cherrypy.request.request_line.split()[1])
if conditions is not None:
username = cherrypy.session.get(SESSION_KEY)
if username:
cherrypy.request.login = username
for condition in conditions:
# A condition is just a callable that returns true or false
if not condition():
raise cherrypy.HTTPRedirect(mylar.CONFIG.HTTP_ROOT + "auth/login?from_page=%s" % get_params)
else:
raise cherrypy.HTTPRedirect(mylar.CONFIG.HTTP_ROOT + "auth/login?from_page=%s" % get_params)
cherrypy.tools.auth = cherrypy.Tool('before_handler', check_auth)
def require(*conditions):
"""A decorator that appends conditions to the auth.require config
variable."""
def decorate(f):
if not hasattr(f, '_cp_config'):
f._cp_config = dict()
if 'auth.require' not in f._cp_config:
f._cp_config['auth.require'] = []
f._cp_config['auth.require'].extend(conditions)
return f
return decorate
# Conditions are callables that return True
# if the user fulfills the conditions they define, False otherwise
#
# They can access the current username as cherrypy.request.login
#
# Define those at will however suits the application.
def member_of(groupname):
def check():
# replace with actual check if <username> is in <groupname>
return cherrypy.request.login == 'joe' and groupname == 'admin'
return check
def name_is(reqd_username):
return lambda: reqd_username == cherrypy.request.login
# These might be handy
def any_of(*conditions):
"""Returns True if any of the conditions match"""
def check():
for c in conditions:
if c():
return True
return False
return check
# By default all conditions are required, but this might still be
# needed if you want to use it inside of an any_of(...) condition
def all_of(*conditions):
"""Returns True if all of the conditions match"""
def check():
for c in conditions:
if not c():
return False
return True
return check
# Controller to provide login and logout actions
class AuthController(object):
def on_login(self, username):
"""Called on successful login"""
logger.info('%s successfully logged on.' % username)
# not needed or used for Mylar currently
def on_logout(self, username):
"""Called on logout"""
# not needed or used for Mylar currently
def get_loginform(self, username, msg="Enter login information", from_page="/"):
from mylar.webserve import serve_template
return serve_template(templatename="login.html", username=escape(username, True), title="Login", from_page=from_page)
@cherrypy.expose
def login(self, current_username=None, current_password=None, remember_me='0', from_page="/"):
if current_username is None or current_password is None:
return self.get_loginform("", from_page=from_page)
error_msg = check_credentials(current_username, current_password)
if error_msg:
return self.get_loginform(current_username, error_msg, from_page)
else:
#if all([from_page != "/", from_page != "//"]):
# from_page = from_page
#if mylar.OS_DETECT == 'Windows':
# if mylar.CONFIG.HTTP_ROOT != "//":
# from_page = re.sub(mylar.CONFIG.HTTP_ROOT, '', from_page,1).strip()
#else:
# #if mylar.CONFIG.HTTP_ROOT != "/":
# from_page = re.sub(mylar.CONFIG.HTTP_ROOT, '', from_page,1).strip()
cherrypy.session.regenerate()
cherrypy.session[SESSION_KEY] = cherrypy.request.login = current_username
#expiry = datetime.now() + (timedelta(days=30) if remember_me == '1' else timedelta(minutes=60))
#cherrypy.session[SESSION_KEY] = {'user': cherrypy.request.login,
# 'expiry': expiry}
self.on_login(current_username)
raise cherrypy.HTTPRedirect(from_page or mylar.CONFIG.HTTP_ROOT)
@cherrypy.expose
def logout(self, from_page="/"):
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
sess[SESSION_KEY] = None
return self.get_loginform("", from_page=from_page)
if username:
cherrypy.request.login = None
self.on_logout(username)
raise cherrypy.HTTPRedirect(from_page or mylar.CONFIG.HTTP_ROOT)
| 6,778 | Python | .py | 153 | 37.542484 | 125 | 0.662023 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,250 | cache.py | evilhero_mylar/mylar/cache.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import os
import glob, urllib, urllib2
import lib.simplejson as simplejson
import mylar
from mylar import db, helpers, logger
class Cache(object):
"""
This class deals with getting, storing and serving up artwork (album
art, artist images, etc) and info/descriptions (album info, artist descrptions)
to and from the cache folder. This can be called from within a web interface,
for example, using the helper functions getInfo(id) and getArtwork(id), to utilize the cached
images rather than having to retrieve them every time the page is reloaded.
So you can call cache.getArtwork(id) which will return an absolute path
to the image file on the local machine, or if the cache directory
doesn't exist, or can not be written to, it will return a url to the image.
Call cache.getInfo(id) to grab the artist/album info; will return the text description
The basic format for art in the cache is <musicbrainzid>.<date>.<ext>
and for info it is <musicbrainzid>.<date>.txt
"""
mylar.CACHE_DIR = os.path.join(str(mylar.PROG_DIR), 'cache/')
path_to_art_cache = os.path.join(mylar.CACHE_DIR, 'artwork')
id = None
id_type = None # 'comic' or 'issue' - set automatically depending on whether ComicID or IssueID is passed
query_type = None # 'artwork','thumb' or 'info' - set automatically
artwork_files = []
thumb_files = []
artwork_errors = False
artwork_url = None
thumb_errors = False
thumb_url = None
def __init__(self):
pass
def _exists(self, type):
self.artwork_files = glob.glob(os.path.join(self.path_to_art_cache, self.id + '*'))
self.thumb_files = glob.glob(os.path.join(self.path_to_art_cache, 'T_' + self.id + '*'))
if type == 'artwork':
if self.artwork_files:
return True
else:
return False
elif type == 'thumb':
if self.thumb_files:
return True
else:
return False
def _get_age(self, date):
# There's probably a better way to do this
split_date = date.split('-')
days_old = int(split_date[0]) *365 + int(split_date[1]) *30 + int(split_date[2])
return days_old
def _is_current(self, filename=None, date=None):
if filename:
base_filename = os.path.basename(filename)
date = base_filename.split('.')[1]
# Calculate how old the cached file is based on todays date & file date stamp
# helpers.today() returns todays date in yyyy-mm-dd format
if self._get_age(helpers.today()) - self._get_age(date) < 30:
return True
else:
return False
def get_artwork_from_cache(self, ComicID=None, imageURL=None):
'''
Pass a comicvine id to this function (either ComicID or IssueID)
'''
self.query_type = 'artwork'
if ComicID:
self.id = ComicID
self.id_type = 'comic'
else:
self.id = IssueID
self.id_type = 'issue'
if self._exists('artwork') and self._is_current(filename=self.artwork_files[0]):
return self.artwork_files[0]
else:
# we already have the image for the comic in the sql db. Simply retrieve it, and save it.
image_url = imageURL
logger.debug('Retrieving comic image from: ' + image_url)
try:
artwork = urllib2.urlopen(image_url, timeout=20).read()
except Exception, e:
logger.error('Unable to open url "' + image_url + '". Error: ' + str(e))
artwork = None
if artwork:
# Make sure the artwork dir exists:
if not os.path.isdir(self.path_to_art_cache):
try:
os.makedirs(self.path_to_art_cache)
except Exception, e:
logger.error('Unable to create artwork cache dir. Error: ' + str(e))
self.artwork_errors = True
self.artwork_url = image_url
#Delete the old stuff
for artwork_file in self.artwork_files:
try:
os.remove(artwork_file)
except:
logger.error('Error deleting file from the cache: ' + artwork_file)
ext = os.path.splitext(image_url)[1]
artwork_path = os.path.join(self.path_to_art_cache, self.id + '.' + helpers.today() + ext)
try:
f = open(artwork_path, 'wb')
f.write(artwork)
f.close()
except Exception, e:
logger.error('Unable to write to the cache dir: ' + str(e))
self.artwork_errors = True
self.artwork_url = image_url
def getArtwork(ComicID=None, imageURL=None):
c = Cache()
artwork_path = c.get_artwork_from_cache(ComicID, imageURL)
logger.info('artwork path at : ' + str(artwork_path))
if not artwork_path:
return None
if artwork_path.startswith('http://'):
return artwork_path
else:
artwork_file = os.path.basename(artwork_path)
return "cache/artwork/" + artwork_file
| 6,033 | Python | .py | 132 | 35.621212 | 110 | 0.606278 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,251 | filers.py | evilhero_mylar/mylar/filers.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import re
import os
import mylar
from mylar import helpers, db, logger
class FileHandlers(object):
def __init__(self, comic=None, issue=None, ComicID=None, IssueID=None):
self.myDB = db.DBConnection()
if ComicID is not None:
self.comicid = ComicID
self.comic = self.myDB.selectone('SELECT * FROM comics WHERE ComicID=?', [ComicID]).fetchone()
elif comic is not None:
self.comic = comic
self.comicid = None
else:
self.comic = None
self.comicid = None
if IssueID is not None:
self.issueid = IssueID
self.issue = self.myDB.select('SELECT * FROM issues WHERE IssueID=?', [IssueID])
elif issue is not None:
self.issue = issue
self.issueid = None
else:
self.issue = None
self.issueid = None
def folder_create(self, booktype=None):
# dictionary needs to passed called comic with {'ComicPublisher', 'CorrectedType, 'Type', 'ComicYear', 'ComicName', 'ComicVersion'}
# or pass in comicid value from __init__
# setup default location here
u_comicnm = self.comic['ComicName']
# let's remove the non-standard characters here that will break filenaming / searching.
comicname_filesafe = helpers.filesafe(u_comicnm)
comicdir = comicname_filesafe
series = comicdir
if series[-1:] == '.':
series[:-1]
publisher = re.sub('!', '', self.comic['ComicPublisher']) # thanks Boom!
publisher = helpers.filesafe(publisher)
if booktype is not None:
if self.comic['Corrected_Type'] is not None:
booktype = self.comic['Corrected_Type']
else:
booktype = booktype
else:
booktype = self.comic['Type']
if any([booktype is None, booktype == 'None', booktype == 'Print']) or all([booktype != 'Print', mylar.CONFIG.FORMAT_BOOKTYPE is False]):
chunk_fb = re.sub('\$Type', '', mylar.CONFIG.FOLDER_FORMAT)
chunk_b = re.compile(r'\s+')
chunk_folder_format = chunk_b.sub(' ', chunk_fb)
else:
chunk_folder_format = mylar.CONFIG.FOLDER_FORMAT
if any([self.comic['ComicVersion'] is None, booktype != 'Print']):
comicVol = 'None'
else:
comicVol = self.comic['ComicVersion']
#if comversion is None, remove it so it doesn't populate with 'None'
if comicVol == 'None':
chunk_f_f = re.sub('\$VolumeN', '', chunk_folder_format)
chunk_f = re.compile(r'\s+')
chunk_folder_format = chunk_f.sub(' ', chunk_f_f)
logger.fdebug('No version # found for series, removing from folder format')
logger.fdebug("new folder format: " + str(chunk_folder_format))
#do work to generate folder path
values = {'$Series': series,
'$Publisher': publisher,
'$Year': self.comic['ComicYear'],
'$series': series.lower(),
'$publisher': publisher.lower(),
'$VolumeY': 'V' + self.comic['ComicYear'],
'$VolumeN': comicVol.upper(),
'$Annual': 'Annual',
'$Type': booktype
}
try:
if mylar.CONFIG.FOLDER_FORMAT == '':
comlocation = os.path.join(mylar.CONFIG.DESTINATION_DIR, comicdir, " (" + comic['SeriesYear'] + ")")
else:
chunk_folder_format = re.sub('[()|[]]', '', chunk_folder_format).strip()
comlocation = os.path.join(mylar.CONFIG.DESTINATION_DIR, helpers.replace_all(chunk_folder_format, values))
except Exception as e:
if 'TypeError' in e:
if mylar.CONFIG.DESTINATION_DIR is None:
logger.error('[ERROR] %s' % e)
logger.error('No Comic Location specified. This NEEDS to be set before anything can be added successfully.')
return
logger.error('[ERROR] %s' % e)
logger.error('Cannot determine Comic Location path properly. Check your Comic Location and Folder Format for any errors.')
return
if mylar.CONFIG.DESTINATION_DIR == "":
logger.error('There is no Comic Location Path specified - please specify one in Config/Web Interface.')
return
#enforce proper slashes here..
cnt1 = comlocation.count('\\')
cnt2 = comlocation.count('/')
if cnt1 > cnt2 and '/' in chunk_folder_format:
comlocation = re.sub('/', '\\', comlocation)
if mylar.CONFIG.REPLACE_SPACES:
#mylar.CONFIG.REPLACE_CHAR ...determines what to replace spaces with underscore or dot
comlocation = comlocation.replace(' ', mylar.CONFIG.REPLACE_CHAR)
return comlocation
def rename_file(self, ofilename, issue=None, annualize=None, arc=False, file_format=None): #comicname, issue, comicyear=None, issueid=None)
comicid = self.comicid # it's coming in unicoded...
issueid = self.issueid
if file_format is None:
file_format = mylar.CONFIG.FILE_FORMAT
logger.fdebug(type(comicid))
logger.fdebug(type(issueid))
logger.fdebug('comicid: %s' % comicid)
logger.fdebug('issue# as per cv: %s' % issue)
logger.fdebug('issueid:' + str(issueid))
if issueid is None:
logger.fdebug('annualize is ' + str(annualize))
if arc:
#this has to be adjusted to be able to include story arc issues that span multiple arcs
chkissue = self.myDB.selectone("SELECT * from storyarcs WHERE ComicID=? AND Issue_Number=?", [comicid, issue]).fetchone()
else:
chkissue = self.myDB.selectone("SELECT * from issues WHERE ComicID=? AND Issue_Number=?", [comicid, issue]).fetchone()
if all([chkissue is None, annualize is None, not mylar.CONFIG.ANNUALS_ON]):
chkissue = self.myDB.selectone("SELECT * from annuals WHERE ComicID=? AND Issue_Number=?", [comicid, issue]).fetchone()
if chkissue is None:
#rechk chkissue against int value of issue #
if arc:
chkissue = self.myDB.selectone("SELECT * from storyarcs WHERE ComicID=? AND Int_IssueNumber=?", [comicid, issuedigits(issue)]).fetchone()
else:
chkissue = self.myDB.selectone("SELECT * from issues WHERE ComicID=? AND Int_IssueNumber=?", [comicid, issuedigits(issue)]).fetchone()
if all([chkissue is None, annualize == 'yes', mylar.CONFIG.ANNUALS_ON]):
chkissue = self.myDB.selectone("SELECT * from annuals WHERE ComicID=? AND Int_IssueNumber=?", [comicid, issuedigits(issue)]).fetchone()
if chkissue is None:
logger.error('Invalid Issue_Number - please validate.')
return
else:
logger.info('Int Issue_number compare found. continuing...')
issueid = chkissue['IssueID']
else:
issueid = chkissue['IssueID']
#use issueid to get publisher, series, year, issue number
logger.fdebug('issueid is now : ' + str(issueid))
if arc:
issueinfo = self.myDB.selectone("SELECT * from storyarcs WHERE ComicID=? AND IssueID=? AND StoryArc=?", [comicid, issueid, arc]).fetchone()
else:
issueinfo = self.myDB.selectone("SELECT * from issues WHERE ComicID=? AND IssueID=?", [comicid, issueid]).fetchone()
if issueinfo is None:
logger.fdebug('not an issue, checking against annuals')
issueinfo = self.myDB.selectone("SELECT * from annuals WHERE ComicID=? AND IssueID=?", [comicid, issueid]).fetchone()
if issueinfo is None:
logger.fdebug('Unable to rename - cannot locate issue id within db')
return
else:
annualize = True
if issueinfo is None:
logger.fdebug('Unable to rename - cannot locate issue id within db')
return
#remap the variables to a common factor.
if arc:
issuenum = issueinfo['IssueNumber']
issuedate = issueinfo['IssueDate']
publisher = issueinfo['IssuePublisher']
series = issueinfo['ComicName']
seriesfilename = series #Alternate FileNaming is not available with story arcs.
seriesyear = issueinfo['SeriesYear']
arcdir = helpers.filesafe(issueinfo['StoryArc'])
if mylar.CONFIG.REPLACE_SPACES:
arcdir = arcdir.replace(' ', mylar.CONFIG.REPLACE_CHAR)
if mylar.CONFIG.STORYARCDIR:
storyarcd = os.path.join(mylar.CONFIG.DESTINATION_DIR, "StoryArcs", arcdir)
logger.fdebug('Story Arc Directory set to : ' + storyarcd)
else:
logger.fdebug('Story Arc Directory set to : ' + mylar.CONFIG.GRABBAG_DIR)
storyarcd = os.path.join(mylar.CONFIG.DESTINATION_DIR, mylar.CONFIG.GRABBAG_DIR)
comlocation = storyarcd
comversion = None #need to populate this.
else:
issuenum = issueinfo['Issue_Number']
issuedate = issueinfo['IssueDate']
publisher = self.comic['ComicPublisher']
series = self.comic['ComicName']
if self.comic['AlternateFileName'] is None or self.comic['AlternateFileName'] == 'None':
seriesfilename = series
else:
seriesfilename = self.comic['AlternateFileName']
logger.fdebug('Alternate File Naming has been enabled for this series. Will rename series title to : ' + seriesfilename)
seriesyear = self.comic['ComicYear']
comlocation = self.comic['ComicLocation']
comversion = self.comic['ComicVersion']
unicodeissue = issuenum
if type(issuenum) == unicode:
vals = {u'\xbd':'.5',u'\xbc':'.25',u'\xbe':'.75',u'\u221e':'9999999999',u'\xe2':'9999999999'}
else:
vals = {'\xbd':'.5','\xbc':'.25','\xbe':'.75','\u221e':'9999999999','\xe2':'9999999999'}
x = [vals[key] for key in vals if key in issuenum]
if x:
issuenum = x[0]
logger.fdebug('issue number formatted: %s' % issuenum)
#comicid = issueinfo['ComicID']
#issueno = str(issuenum).split('.')[0]
issue_except = 'None'
issue_exceptions = ['AU',
'INH',
'NOW',
'AI',
'MU',
'A',
'B',
'C',
'X',
'O']
valid_spaces = ('.', '-')
for issexcept in issue_exceptions:
if issexcept.lower() in issuenum.lower():
logger.fdebug('ALPHANUMERIC EXCEPTION : [' + issexcept + ']')
v_chk = [v for v in valid_spaces if v in issuenum]
if v_chk:
iss_space = v_chk[0]
logger.fdebug('character space denoted as : ' + iss_space)
else:
logger.fdebug('character space not denoted.')
iss_space = ''
# if issexcept == 'INH':
# issue_except = '.INH'
if issexcept == 'NOW':
if '!' in issuenum: issuenum = re.sub('\!', '', issuenum)
# issue_except = '.NOW'
issue_except = iss_space + issexcept
logger.fdebug('issue_except denoted as : ' + issue_except)
issuenum = re.sub("[^0-9]", "", issuenum)
break
# if 'au' in issuenum.lower() and issuenum[:1].isdigit():
# issue_except = ' AU'
# elif 'ai' in issuenum.lower() and issuenum[:1].isdigit():
# issuenum = re.sub("[^0-9]", "", issuenum)
# issue_except = ' AI'
# elif 'inh' in issuenum.lower() and issuenum[:1].isdigit():
# issuenum = re.sub("[^0-9]", "", issuenum)
# issue_except = '.INH'
# elif 'now' in issuenum.lower() and issuenum[:1].isdigit():
# if '!' in issuenum: issuenum = re.sub('\!', '', issuenum)
# issuenum = re.sub("[^0-9]", "", issuenum)
# issue_except = '.NOW'
if '.' in issuenum:
iss_find = issuenum.find('.')
iss_b4dec = issuenum[:iss_find]
if iss_find == 0:
iss_b4dec = '0'
iss_decval = issuenum[iss_find +1:]
if iss_decval.endswith('.'):
iss_decval = iss_decval[:-1]
if int(iss_decval) == 0:
iss = iss_b4dec
issdec = int(iss_decval)
issueno = iss
else:
if len(iss_decval) == 1:
iss = iss_b4dec + "." + iss_decval
issdec = int(iss_decval) * 10
else:
iss = iss_b4dec + "." + iss_decval.rstrip('0')
issdec = int(iss_decval.rstrip('0')) * 10
issueno = iss_b4dec
else:
iss = issuenum
issueno = iss
# issue zero-suppression here
if mylar.CONFIG.ZERO_LEVEL == "0":
zeroadd = ""
else:
if mylar.CONFIG.ZERO_LEVEL_N == "none": zeroadd = ""
elif mylar.CONFIG.ZERO_LEVEL_N == "0x": zeroadd = "0"
elif mylar.CONFIG.ZERO_LEVEL_N == "00x": zeroadd = "00"
logger.fdebug('Zero Suppression set to : ' + str(mylar.CONFIG.ZERO_LEVEL_N))
prettycomiss = None
if issueno.isalpha():
logger.fdebug('issue detected as an alpha.')
prettycomiss = str(issueno)
else:
try:
x = float(issuenum)
#validity check
if x < 0:
logger.info('I\'ve encountered a negative issue #: %s. Trying to accomodate.' % issueno)
prettycomiss = '-' + str(zeroadd) + str(issueno[1:])
elif x == 9999999999:
logger.fdebug('Infinity issue found.')
issuenum = 'infinity'
elif x >= 0:
pass
else:
raise ValueError
except ValueError, e:
logger.warn('Unable to properly determine issue number [ %s] - you should probably log this on github for help.' % issueno)
return
if prettycomiss is None and len(str(issueno)) > 0:
#if int(issueno) < 0:
# self._log("issue detected is a negative")
# prettycomiss = '-' + str(zeroadd) + str(abs(issueno))
if int(issueno) < 10:
logger.fdebug('issue detected less than 10')
if '.' in iss:
if int(iss_decval) > 0:
issueno = str(iss)
prettycomiss = str(zeroadd) + str(iss)
else:
prettycomiss = str(zeroadd) + str(int(issueno))
else:
prettycomiss = str(zeroadd) + str(iss)
if issue_except != 'None':
prettycomiss = str(prettycomiss) + issue_except
logger.fdebug('Zero level supplement set to ' + str(mylar.CONFIG.ZERO_LEVEL_N) + '. Issue will be set as : ' + str(prettycomiss))
elif int(issueno) >= 10 and int(issueno) < 100:
logger.fdebug('issue detected greater than 10, but less than 100')
if mylar.CONFIG.ZERO_LEVEL_N == "none":
zeroadd = ""
else:
zeroadd = "0"
if '.' in iss:
if int(iss_decval) > 0:
issueno = str(iss)
prettycomiss = str(zeroadd) + str(iss)
else:
prettycomiss = str(zeroadd) + str(int(issueno))
else:
prettycomiss = str(zeroadd) + str(iss)
if issue_except != 'None':
prettycomiss = str(prettycomiss) + issue_except
logger.fdebug('Zero level supplement set to ' + str(mylar.CONFIG.ZERO_LEVEL_N) + '.Issue will be set as : ' + str(prettycomiss))
else:
logger.fdebug('issue detected greater than 100')
if issuenum == 'infinity':
prettycomiss = 'infinity'
else:
if '.' in iss:
if int(iss_decval) > 0:
issueno = str(iss)
prettycomiss = str(issueno)
if issue_except != 'None':
prettycomiss = str(prettycomiss) + issue_except
logger.fdebug('Zero level supplement set to ' + str(mylar.CONFIG.ZERO_LEVEL_N) + '. Issue will be set as : ' + str(prettycomiss))
elif len(str(issueno)) == 0:
prettycomiss = str(issueno)
logger.fdebug('issue length error - cannot determine length. Defaulting to None: ' + str(prettycomiss))
logger.fdebug('Pretty Comic Issue is : ' + str(prettycomiss))
if mylar.CONFIG.UNICODE_ISSUENUMBER:
logger.fdebug('Setting this to Unicode format as requested: %s' % prettycomiss)
prettycomiss = unicodeissue
issueyear = issuedate[:4]
month = issuedate[5:7].replace('-', '').strip()
month_name = helpers.fullmonth(month)
if month_name is None:
month_name = 'None'
logger.fdebug('Issue Year : ' + str(issueyear))
logger.fdebug('Publisher: ' + publisher)
logger.fdebug('Series: ' + series)
logger.fdebug('Year: ' + str(seriesyear))
logger.fdebug('Comic Location: ' + comlocation)
if self.comic['Corrected_Type'] is not None:
if self.comic['Type'] != self.comic['Corrected_Type']:
booktype = self.comic['Corrected_Type']
else:
booktype = self.comic['Type']
else:
booktype = self.comic['Type']
if booktype == 'Print' or all([booktype != 'Print', mylar.CONFIG.FORMAT_BOOKTYPE is False]):
chunk_fb = re.sub('\$Type', '', file_format)
chunk_b = re.compile(r'\s+')
chunk_file_format = chunk_b.sub(' ', chunk_fb)
else:
chunk_file_format = file_format
if any([comversion is None, booktype != 'Print']):
comversion = 'None'
#if comversion is None, remove it so it doesn't populate with 'None'
if comversion == 'None':
chunk_f_f = re.sub('\$VolumeN', '', chunk_file_format)
chunk_f = re.compile(r'\s+')
chunk_file_format = chunk_f.sub(' ', chunk_f_f)
logger.fdebug('No version # found for series, removing from filename')
logger.fdebug("new format: " + str(chunk_file_format))
if annualize is None:
chunk_f_f = re.sub('\$Annual', '', chunk_file_format)
chunk_f = re.compile(r'\s+')
chunk_file_format = chunk_f.sub(' ', chunk_f_f)
logger.fdebug('not an annual - removing from filename paramaters')
logger.fdebug('new format: ' + str(chunk_file_format))
else:
logger.fdebug('chunk_file_format is: ' + str(chunk_file_format))
if mylar.CONFIG.ANNUALS_ON:
if 'annual' in series.lower():
if '$Annual' not in chunk_file_format: # and 'annual' not in ofilename.lower():
#if it's an annual, but $annual isn't specified in file_format, we need to
#force it in there, by default in the format of $Annual $Issue
#prettycomiss = "Annual " + str(prettycomiss)
logger.fdebug('[%s][ANNUALS-ON][ANNUAL IN SERIES][NO ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
#because it exists within title, strip it then use formatting tag for placement of wording.
chunk_f_f = re.sub('\$Annual', '', chunk_file_format)
chunk_f = re.compile(r'\s+')
chunk_file_format = chunk_f.sub(' ', chunk_f_f)
logger.fdebug('[%s][ANNUALS-ON][ANNUAL IN SERIES][ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
if '$Annual' not in chunk_file_format: # and 'annual' not in ofilename.lower():
#if it's an annual, but $annual isn't specified in file_format, we need to
#force it in there, by default in the format of $Annual $Issue
prettycomiss = "Annual %s" % prettycomiss
logger.fdebug('[%s][ANNUALS-ON][ANNUAL NOT IN SERIES][NO ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
logger.fdebug('[%s][ANNUALS-ON][ANNUAL NOT IN SERIES][ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
#if annuals aren't enabled, then annuals are being tracked as independent series.
#annualize will be true since it's an annual in the seriesname.
if 'annual' in series.lower():
if '$Annual' not in chunk_file_format: # and 'annual' not in ofilename.lower():
#if it's an annual, but $annual isn't specified in file_format, we need to
#force it in there, by default in the format of $Annual $Issue
#prettycomiss = "Annual " + str(prettycomiss)
logger.fdebug('[%s][ANNUALS-OFF][ANNUAL IN SERIES][NO ANNUAL FORMAT] prettycomiss: %s' (series, prettycomiss))
else:
#because it exists within title, strip it then use formatting tag for placement of wording.
chunk_f_f = re.sub('\$Annual', '', chunk_file_format)
chunk_f = re.compile(r'\s+')
chunk_file_format = chunk_f.sub(' ', chunk_f_f)
logger.fdebug('[%s][ANNUALS-OFF][ANNUAL IN SERIES][ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
if '$Annual' not in chunk_file_format: # and 'annual' not in ofilename.lower():
#if it's an annual, but $annual isn't specified in file_format, we need to
#force it in there, by default in the format of $Annual $Issue
prettycomiss = "Annual %s" % prettycomiss
logger.fdebug('[%s][ANNUALS-OFF][ANNUAL NOT IN SERIES][NO ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
logger.fdebug('[%s][ANNUALS-OFF][ANNUAL NOT IN SERIES][ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
logger.fdebug('Annual detected within series title of ' + series + '. Not auto-correcting issue #')
seriesfilename = seriesfilename.encode('ascii', 'ignore').strip()
filebad = [':', ',', '/', '?', '!', '\'', '\"', '\*'] #in u_comicname or '/' in u_comicname or ',' in u_comicname or '?' in u_comicname:
for dbd in filebad:
if dbd in seriesfilename:
if any([dbd == '/', dbd == '*']):
repthechar = '-'
else:
repthechar = ''
seriesfilename = seriesfilename.replace(dbd, repthechar)
logger.fdebug('Altering series name due to filenaming restrictions: ' + seriesfilename)
publisher = re.sub('!', '', publisher)
file_values = {'$Series': seriesfilename,
'$Issue': prettycomiss,
'$Year': issueyear,
'$series': series.lower(),
'$Publisher': publisher,
'$publisher': publisher.lower(),
'$VolumeY': 'V' + str(seriesyear),
'$VolumeN': comversion,
'$monthname': month_name,
'$month': month,
'$Annual': 'Annual',
'$Type': booktype
}
extensions = ('.cbr', '.cbz', '.cb7')
if ofilename.lower().endswith(extensions):
path, ext = os.path.splitext(ofilename)
if file_format == '':
logger.fdebug('Rename Files is not enabled - keeping original filename.')
#check if extension is in nzb_name - will screw up otherwise
if ofilename.lower().endswith(extensions):
nfilename = ofilename[:-4]
else:
nfilename = ofilename
else:
chunk_file_format = re.sub('[()|[]]', '', chunk_file_format).strip()
nfilename = helpers.replace_all(chunk_file_format, file_values)
if mylar.CONFIG.REPLACE_SPACES:
#mylar.CONFIG.REPLACE_CHAR ...determines what to replace spaces with underscore or dot
nfilename = nfilename.replace(' ', mylar.CONFIG.REPLACE_CHAR)
nfilename = re.sub('[\,\:]', '', nfilename) + ext.lower()
logger.fdebug('New Filename: ' + nfilename)
if mylar.CONFIG.LOWERCASE_FILENAMES:
nfilename = nfilename.lower()
dst = os.path.join(comlocation, nfilename)
else:
dst = os.path.join(comlocation, nfilename)
logger.fdebug('Source: ' + ofilename)
logger.fdebug('Destination: ' + dst)
rename_this = {"destination_dir": dst,
"nfilename": nfilename,
"issueid": issueid,
"comicid": comicid}
return rename_this
| 28,615 | Python | .py | 498 | 40.096386 | 163 | 0.511745 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,252 | solicit.py | evilhero_mylar/mylar/solicit.py |
from bs4 import BeautifulSoup, UnicodeDammit
import urllib2
import csv
import fileinput
import sys
import re
import os
import sqlite3
import datetime
import unicodedata
from decimal import Decimal
from HTMLParser import HTMLParseError
from time import strptime
import mylar
from mylar import logger, helpers
def solicit(month, year):
#convert to numerics just to ensure this...
month = int(month)
year = int(year)
#print ( "month: " + str(month) )
#print ( "year: " + str(year) )
# in order to gather ALL upcoming - let's start to loop through months going ahead one at a time
# until we get a null then break. (Usually not more than 3 months in advance is available)
mnloop = 0
upcoming = []
publishers = {'DC Comics': 'DC Comics', 'DC\'s': 'DC Comics', 'Marvel': 'Marvel Comics', 'Image': 'Image Comics', 'IDW': 'IDW Publishing', 'Dark Horse': 'Dark Horse'}
# -- this is no longer needed (testing)
# while (mnloop < 5):
# if year == 2014:
# if len(str(month)) == 1:
# month_string = '0' + str(month)
# else:
# month_string = str(month)
# datestring = str(year) + str(month_string)
# else:
# datestring = str(month) + str(year)
# pagelinks = "http://www.comicbookresources.com/tag/solicits" + str(datestring)
#using the solicits+datestring leaves out some entries occasionally
#should use http://www.comicbookresources.com/tag/solicitations
#then just use the logic below but instead of datestring, find the month term and
#go ahead up to +5 months.
if month > 0:
month_start = month
month_end = month + 5
#if month_end > 12:
# ms = 8, me=13 [(12-8)+(13-12)] = [4 + 1] = 5
# [(12 - ms) + (me - 12)] = number of months (5)
monthlist = []
mongr = month_start
#we need to build the months we can grab, but the non-numeric way.
while (mongr <= month_end):
mon = mongr
if mon == 13:
mon = 1
year +=1
if len(str(mon)) == 1:
mon = '0' + str(mon)
monthlist.append({"month": helpers.fullmonth(str(mon)).lower(),
"num_month": mon,
"year": str(year)})
mongr+=1
logger.info('months: ' + str(monthlist))
pagelinks = "http://www.comicbookresources.com/tag/solicitations"
#logger.info('datestring:' + datestring)
#logger.info('checking:' + pagelinks)
pageresponse = urllib2.urlopen (pagelinks)
soup = BeautifulSoup (pageresponse)
cntlinks = soup.findAll('h3')
lenlinks = len(cntlinks)
#logger.info( str(lenlinks) + ' results' )
publish = []
resultURL = []
resultmonth = []
resultyear = []
x = 0
cnt = 0
while (x < lenlinks):
headt = cntlinks[x] #iterate through the hrefs pulling out only results.
if "/?page=article&id=" in str(headt):
#print ("titlet: " + str(headt))
headName = headt.findNext(text=True)
#print ('headName: ' + headName)
if 'Image' in headName: print 'IMAGE FOUND'
if not all(['Marvel' in headName, 'DC' in headName, 'Image' in headName]) and ('Solicitations' in headName or 'Solicits' in headName):
# test for month here (int(month) + 5)
if not any(d.get('month', None) == str(headName).lower() for d in monthlist):
for mt in monthlist:
if mt['month'] in headName.lower():
logger.info('matched on month: ' + str(mt['month']))
logger.info('matched on year: ' + str(mt['year']))
resultmonth.append(mt['num_month'])
resultyear.append(mt['year'])
pubstart = headName.find('Solicitations')
publishchk = False
for pub in publishers:
if pub in headName[:pubstart]:
#print 'publisher:' + str(publishers[pub])
publish.append(publishers[pub])
publishchk = True
break
if publishchk == False:
break
#publish.append( headName[:pubstart].strip() )
abc = headt.findAll('a', href=True)[0]
ID_som = abc['href'] #first instance will have the right link...
resultURL.append(ID_som)
#print '(' + str(cnt) + ') [ ' + publish[cnt] + '] Link URL: ' + resultURL[cnt]
cnt+=1
else:
logger.info('incorrect month - not using.')
x+=1
if cnt == 0:
return #break # no results means, end it
loopthis = (cnt -1)
#this loops through each 'found' solicit page
#shipdate = str(month_string) + '-' + str(year) - not needed.
while (loopthis >= 0):
#print 'loopthis is : ' + str(loopthis)
#print 'resultURL is : ' + str(resultURL[loopthis])
shipdate = str(resultmonth[loopthis]) + '-' + str(resultyear[loopthis])
upcoming += populate(resultURL[loopthis], publish[loopthis], shipdate)
loopthis -=1
logger.info(str(len(upcoming)) + ' upcoming issues discovered.')
newfl = mylar.CACHE_DIR + "/future-releases.txt"
newtxtfile = open(newfl, 'wb')
cntr = 1
for row in upcoming:
if row['Extra'] is None or row['Extra'] == '':
extrarow = 'N/A'
else:
extrarow = row['Extra']
newtxtfile.write(str(row['Shipdate']) + '\t' + str(row['Publisher']) + '\t' + str(row['Issue']) + '\t' + str(row['Comic']) + '\t' + str(extrarow) + '\tSkipped' + '\t' + str(cntr) + '\n')
cntr +=1
newtxtfile.close()
logger.fdebug('attempting to populate future upcoming...')
mylardb = os.path.join(mylar.DATA_DIR, "mylar.db")
connection = sqlite3.connect(str(mylardb))
cursor = connection.cursor()
# we should extract the issues that are being watched, but no data is available yet ('Watch For' status)
# once we get the data, store it, wipe the existing table, retrieve the new data, populate the data into
# the table, recheck the series against the current watchlist and then restore the Watch For data.
cursor.executescript('drop table if exists future;')
cursor.execute("CREATE TABLE IF NOT EXISTS future (SHIPDATE, PUBLISHER text, ISSUE text, COMIC VARCHAR(150), EXTRA text, STATUS text, FutureID text, ComicID text);")
connection.commit()
csvfile = open(newfl, "rb")
creader = csv.reader(csvfile, delimiter='\t')
t = 1
for row in creader:
try:
#print ("Row: %s" % row)
cursor.execute("INSERT INTO future VALUES (?,?,?,?,?,?,?,null);", row)
except Exception, e:
logger.fdebug("Error - invald arguments...-skipping")
pass
t+=1
logger.fdebug('successfully added ' + str(t) + ' issues to future upcoming table.')
csvfile.close()
connection.commit()
connection.close()
mylar.weeklypull.pullitcheck(futurepull="yes")
#.end
def populate(link, publisher, shipdate):
#this is the secondary url call to populate
input = 'http://www.comicbookresources.com/' + link
#print 'checking ' + str(input)
response = urllib2.urlopen (input)
soup = BeautifulSoup (response)
abc = soup.findAll('p')
lenabc = len(abc)
i=0
resultName = []
resultID = []
resultURL = []
matched = "no"
upcome = []
get_next = False
prev_chk = False
while (i < lenabc):
titlet = abc[i] #iterate through the p pulling out only results.
titlet_next = titlet.findNext(text=True)
#print ("titlet: " + str(titlet))
if "/prev_img.php?pid" in str(titlet) and titlet_next is None:
#solicits in 03-2014 have seperated <p> tags, so we need to take the subsequent <p>, not the initial.
prev_chk = False
get_next = True
i+=1
continue
elif titlet_next is not None:
#logger.fdebug('non seperated <p> tags - taking next text.')
get_next = False
prev_chk = True
elif "/news/preview2.php" in str(titlet):
prev_chk = True
get_next = False
elif get_next == True:
prev_chk = True
else:
prev_chk = False
get_next = False
if prev_chk == True:
tempName = titlet.findNext(text=True)
if not any([' TPB' in tempName, 'HC' in tempName, 'GN-TPB' in tempName, 'for $1' in tempName.lower(), 'subscription variant' in tempName.lower(), 'poster' in tempName.lower()]):
if '#' in tempName[:50]:
#tempName = tempName.replace(u'.',u"'")
tempName = tempName.encode('ascii', 'replace') #.decode('utf-8')
if '???' in tempName:
tempName = tempName.replace('???', ' ')
stissue = tempName.find('#')
endissue = tempName.find(' ', stissue)
if tempName[stissue +1] == ' ': #if issue has space between # and number, adjust.
endissue = tempName.find(' ', stissue +2)
if endissue == -1: endissue = len(tempName)
issue = tempName[stissue:endissue].lstrip(' ')
if ':'in issue: issue = re.sub(':', '', issue).rstrip()
exinfo = tempName[endissue:].lstrip(' ')
issue1 = None
issue2 = None
if '-' in issue:
#print ('multiple issues detected. Splitting.')
ststart = issue.find('-')
issue1 = issue[:ststart]
issue2 = '#' + str(issue[ststart +1:])
if '&' in exinfo:
#print ('multiple issues detected. Splitting.')
ststart = exinfo.find('&')
issue1 = issue # this detects fine
issue2 = '#' + str(exinfo[ststart +1:])
if '& ' in issue2: issue2 = re.sub("&\\b", "", issue2)
exinfo = exinfo.replace(exinfo[ststart +1:len(issue2)], '').strip()
if exinfo == '&': exinfo = 'N/A'
comic = tempName[:stissue].strip()
if 'for \$1' in comic:
exinfo = 'for $1'
comic = comic.replace('for \$1\:', '').lstrip()
issuedate = shipdate
if 'on sale' in str(titlet).lower():
onsale_start = str(titlet).lower().find('on sale') + 8
onsale_end = str(titlet).lower().find('<br>', onsale_start)
thedate = str(titlet)[onsale_start:onsale_end]
m = None
basemonths = {'january': '1', 'jan': '1', 'february': '2', 'feb': '2', 'march': '3', 'mar': '3', 'april': '4', 'apr': '4', 'may': '5', 'june': '6', 'july': '7', 'august': '8', 'aug': '8', 'september': '9', 'sept': '9', 'october': '10', 'oct': '10', 'november': '11', 'nov': '11', 'december': '12', 'dec': '12'}
for month in basemonths:
if month in thedate.lower():
m = basemonths[month]
monthname = month
break
if m is not None:
theday = len(month) + 1 # account for space between month & day
thedaystart = thedate[theday:(theday +2)].strip() # day numeric won't exceed 2
if len(str(thedaystart)) == 1:
thedaystart = '0' + str(thedaystart)
if len(str(m)) == 1:
m = '0' + str(m)
thedate = shipdate[-4:] + '-' + str(m) + '-' + str(thedaystart)
logger.info('[' + comic + '] On sale :' + str(thedate))
exinfo += ' [' + str(thedate) + ']'
issuedate = thedate
if issue1:
upcome.append({
'Shipdate': issuedate,
'Publisher': publisher.upper(),
'Issue': re.sub('#', '', issue1).lstrip(),
'Comic': comic.upper(),
'Extra': exinfo.upper()
})
#print ('Comic: ' + comic)
#print('issue#: ' + re.sub('#', '', issue1))
#print ('extra info: ' + exinfo)
if issue2:
upcome.append({
'Shipdate': issuedate,
'Publisher': publisher.upper(),
'Issue': re.sub('#', '', issue2).lstrip(),
'Comic': comic.upper(),
'Extra': exinfo.upper()
})
#print ('Comic: ' + comic)
#print('issue#: ' + re.sub('#', '', issue2))
#print ('extra info: ' + exinfo)
else:
upcome.append({
'Shipdate': issuedate,
'Publisher': publisher.upper(),
'Issue': re.sub('#', '', issue).lstrip(),
'Comic': comic.upper(),
'Extra': exinfo.upper()
})
#print ('Comic: ' + comic)
#print ('issue#: ' + re.sub('#', '', issue))
#print ('extra info: ' + exinfo)
else:
pass
#print ('no issue # to retrieve.')
i+=1
return upcome
#end.
if __name__ == '__main__':
solicit(sys.argv[1], sys.argv[2])
| 14,898 | Python | .py | 298 | 34.325503 | 334 | 0.481155 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,253 | __init__.py | evilhero_mylar/mylar/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import os, sys, subprocess
import threading
import datetime
from datetime import timedelta
import webbrowser
import sqlite3
import itertools
import csv
import shutil
import Queue
import platform
import locale
import re
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
import cherrypy
from mylar import logger, versioncheckit, rsscheckit, searchit, weeklypullit, PostProcessor, updater, helpers
import mylar.config
#these are the globals that are runtime-based (ie. not config-valued at all)
#they are referenced in other modules just as mylar.VARIABLE (instead of mylar.CONFIG.VARIABLE)
PROG_DIR = None
DATA_DIR = None
FULL_PATH = None
MAINTENANCE = False
LOG_DIR = None
LOGTYPE = 'log'
LOG_LANG = 'en'
LOG_CHARSET = 'UTF-8'
LOG_LEVEL = 1
LOGLIST = []
ARGS = None
SIGNAL = None
SYS_ENCODING = None
OS_DETECT = platform.system()
USER_AGENT = None
#VERBOSE = False
DAEMON = False
PIDFILE= None
CREATEPID = False
QUIET=False
MAX_LOGSIZE = 5000000
SAFESTART = False
NOWEEKLY = False
INIT_LOCK = threading.Lock()
IMPORTLOCK = False
IMPORTBUTTON = False
DONATEBUTTON = False
IMPORT_STATUS = None
IMPORT_FILES = 0
IMPORT_TOTALFILES = 0
IMPORT_CID_COUNT = 0
IMPORT_PARSED_COUNT = 0
IMPORT_FAILURE_COUNT = 0
CHECKENABLED = False
_INITIALIZED = False
started = False
MONITOR_STATUS = 'Waiting'
SEARCH_STATUS = 'Waiting'
RSS_STATUS = 'Waiting'
WEEKLY_STATUS = 'Waiting'
VERSION_STATUS = 'Waiting'
UPDATER_STATUS = 'Waiting'
SCHED_RSS_LAST = None
SCHED_WEEKLY_LAST = None
SCHED_MONITOR_LAST = None
SCHED_SEARCH_LAST = None
SCHED_VERSION_LAST = None
SCHED_DBUPDATE_LAST = None
DBUPDATE_INTERVAL = 5
DBLOCK = False
DB_FILE = None
UMASK = None
WANTED_TAB_OFF = False
PULLNEW = None
CONFIG = None
CONFIG_FILE = None
CV_HEADERS = None
CVURL = None
EXPURL = None
DEMURL = None
WWTURL = None
WWT_CF_COOKIEVALUE = None
KEYS_32P = None
AUTHKEY_32P = None
FEED_32P = None
FEEDINFO_32P = None
INKDROPS_32P = None
USE_SABNZBD = False
USE_NZBGET = False
USE_BLACKHOLE = False
USE_RTORRENT = False
USE_DELUGE = False
USE_TRANSMISSION = False
USE_QBITTORENT = False
USE_UTORRENT = False
USE_WATCHDIR = False
SNPOOL = None
NZBPOOL = None
SEARCHPOOL = None
PPPOOL = None
DDLPOOL = None
SNATCHED_QUEUE = Queue.Queue()
NZB_QUEUE = Queue.Queue()
PP_QUEUE = Queue.Queue()
SEARCH_QUEUE = Queue.Queue()
DDL_QUEUE = Queue.Queue()
SEARCH_TIER_DATE = None
COMICSORT = None
PULLBYFILE = False
CFG = None
CURRENT_WEEKNUMBER = None
CURRENT_YEAR = None
INSTALL_TYPE = None
CURRENT_BRANCH = None
CURRENT_VERSION = None
LATEST_VERSION = None
COMMITS_BEHIND = None
LOCAL_IP = None
DOWNLOAD_APIKEY = None
APILOCK = False
SEARCHLOCK = False
DDL_LOCK = False
CMTAGGER_PATH = None
STATIC_COMICRN_VERSION = "1.01"
STATIC_APC_VERSION = "2.04"
SAB_PARAMS = None
COMICINFO = []
SCHED = BackgroundScheduler({
'apscheduler.executors.default': {
'class': 'apscheduler.executors.pool:ThreadPoolExecutor',
'max_workers': '20'
},
'apscheduler.job_defaults.coalesce': 'true',
'apscheduler.job_defaults.max_instances': '3',
'apscheduler.timezone': 'UTC'})
def initialize(config_file):
with INIT_LOCK:
global CONFIG, _INITIALIZED, QUIET, CONFIG_FILE, OS_DETECT, MAINTENANCE, CURRENT_VERSION, LATEST_VERSION, COMMITS_BEHIND, INSTALL_TYPE, IMPORTLOCK, PULLBYFILE, INKDROPS_32P, \
DONATEBUTTON, CURRENT_WEEKNUMBER, CURRENT_YEAR, UMASK, USER_AGENT, SNATCHED_QUEUE, NZB_QUEUE, PP_QUEUE, SEARCH_QUEUE, DDL_QUEUE, PULLNEW, COMICSORT, WANTED_TAB_OFF, CV_HEADERS, \
IMPORTBUTTON, IMPORT_FILES, IMPORT_TOTALFILES, IMPORT_CID_COUNT, IMPORT_PARSED_COUNT, IMPORT_FAILURE_COUNT, CHECKENABLED, CVURL, DEMURL, EXPURL, WWTURL, WWT_CF_COOKIEVALUE, \
DDLPOOL, NZBPOOL, SNPOOL, PPPOOL, SEARCHPOOL, \
USE_SABNZBD, USE_NZBGET, USE_BLACKHOLE, USE_RTORRENT, USE_UTORRENT, USE_QBITTORRENT, USE_DELUGE, USE_TRANSMISSION, USE_WATCHDIR, SAB_PARAMS, \
PROG_DIR, DATA_DIR, CMTAGGER_PATH, DOWNLOAD_APIKEY, LOCAL_IP, STATIC_COMICRN_VERSION, STATIC_APC_VERSION, KEYS_32P, AUTHKEY_32P, FEED_32P, FEEDINFO_32P, \
MONITOR_STATUS, SEARCH_STATUS, RSS_STATUS, WEEKLY_STATUS, VERSION_STATUS, UPDATER_STATUS, DBUPDATE_INTERVAL, LOG_LANG, LOG_CHARSET, APILOCK, SEARCHLOCK, DDL_LOCK, LOG_LEVEL, \
SCHED_RSS_LAST, SCHED_WEEKLY_LAST, SCHED_MONITOR_LAST, SCHED_SEARCH_LAST, SCHED_VERSION_LAST, SCHED_DBUPDATE_LAST, COMICINFO, SEARCH_TIER_DATE
cc = mylar.config.Config(config_file)
CONFIG = cc.read(startup=True)
assert CONFIG is not None
if _INITIALIZED:
return False
# Initialize the database
logger.info('Checking to see if the database has all tables....')
try:
dbcheck()
except Exception, e:
logger.error('Cannot connect to the database: %s' % e)
if MAINTENANCE is False:
#try to get the local IP using socket. Get this on every startup so it's at least current for existing session.
import socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
LOCAL_IP = s.getsockname()[0]
s.close()
logger.info('Successfully discovered local IP and locking it in as : ' + str(LOCAL_IP))
except:
logger.warn('Unable to determine local IP - this might cause problems when downloading (maybe use host_return in the config.ini)')
LOCAL_IP = CONFIG.HTTP_HOST
# verbatim back the logger being used since it's now started.
if LOGTYPE == 'clog':
logprog = 'Concurrent Rotational Log Handler'
else:
logprog = 'Rotational Log Handler (default)'
logger.fdebug('Logger set to use : ' + logprog)
if LOGTYPE == 'log' and OS_DETECT == 'Windows':
logger.fdebug('ConcurrentLogHandler package not installed. Using builtin log handler for Rotational logs (default)')
logger.fdebug('[Windows Users] If you are experiencing log file locking and want this auto-enabled, you need to install Python Extensions for Windows ( http://sourceforge.net/projects/pywin32/ )')
#check for syno_fix here
if CONFIG.SYNO_FIX:
parsepath = os.path.join(DATA_DIR, 'bs4', 'builder', '_lxml.py')
if os.path.isfile(parsepath):
print ("found bs4...renaming appropriate file.")
src = os.path.join(parsepath)
dst = os.path.join(DATA_DIR, 'bs4', 'builder', 'lxml.py')
try:
shutil.move(src, dst)
except (OSError, IOError):
logger.error('Unable to rename file...shutdown Mylar and go to ' + src.encode('utf-8') + ' and rename the _lxml.py file to lxml.py')
logger.error('NOT doing this will result in errors when adding / refreshing a series')
else:
logger.info('Synology Parsing Fix already implemented. No changes required at this time.')
CV_HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'}
# set the current week for the pull-list
todaydate = datetime.datetime.today()
CURRENT_WEEKNUMBER = todaydate.strftime("%U")
CURRENT_YEAR = todaydate.strftime("%Y")
if SEARCH_TIER_DATE is None:
#tier the wanted listed so anything older than 14 days won't trigger the API during searches.
#utc_date = datetime.datetime.utcnow()
STD = todaydate - timedelta(days = 14)
SEARCH_TIER_DATE = STD.strftime('%Y-%m-%d')
logger.fdebug('SEARCH_TIER_DATE set to : %s' % SEARCH_TIER_DATE)
#set the default URL for ComicVine API here.
CVURL = 'https://comicvine.gamespot.com/api/'
#set default URL for Public trackers (just in case it changes more frequently)
WWTURL = 'https://worldwidetorrents.to/'
DEMURL = 'https://www.demonoid.pw/'
#set the default URL for nzbindex
EXPURL = 'https://nzbindex.nl/'
if CONFIG.LOCMOVE:
helpers.updateComicLocation()
#Ordering comics here
if mylar.MAINTENANCE is False:
logger.info('Remapping the sorting to allow for new additions.')
COMICSORT = helpers.ComicSort(sequence='startup')
# Store the original umask
UMASK = os.umask(0)
os.umask(UMASK)
_INITIALIZED = True
return True
def daemonize():
if threading.activeCount() != 1:
logger.warn('There are %r active threads. Daemonizing may cause \
strange behavior.' % threading.enumerate())
sys.stdout.flush()
sys.stderr.flush()
# Do first fork
try:
pid = os.fork()
if pid == 0:
pass
else:
# Exit the parent process
logger.debug('Forking once...')
os._exit(0)
except OSError, e:
sys.exit("1st fork failed: %s [%d]" % (e.strerror, e.errno))
os.setsid()
# Make sure I can read my own files and shut out others
prev = os.umask(0) # @UndefinedVariable - only available in UNIX
os.umask(prev and int('077', 8))
# Do second fork
try:
pid = os.fork()
if pid > 0:
logger.debug('Forking twice...')
os._exit(0) # Exit second parent process
except OSError, e:
sys.exit("2nd fork failed: %s [%d]" % (e.strerror, e.errno))
dev_null = file('/dev/null', 'r')
os.dup2(dev_null.fileno(), sys.stdin.fileno())
si = open('/dev/null', "r")
so = open('/dev/null', "a+")
se = open('/dev/null', "a+")
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
pid = os.getpid()
logger.info('Daemonized to PID: %s' % pid)
if CREATEPID:
logger.info("Writing PID %d to %s", pid, PIDFILE)
with file(PIDFILE, 'w') as fp:
fp.write("%s\n" % pid)
def launch_browser(host, port, root):
if host == '0.0.0.0':
host = 'localhost'
try:
webbrowser.open('http://%s:%i%s' % (host, port, root))
except Exception, e:
logger.error('Could not launch browser: %s' % e)
def start():
global _INITIALIZED, started
with INIT_LOCK:
if _INITIALIZED:
#load up the previous runs from the job sql table so we know stuff...
monitors = helpers.job_management()
SCHED_WEEKLY_LAST = monitors['weekly']
SCHED_SEARCH_LAST = monitors['search']
SCHED_UPDATER_LAST = monitors['dbupdater']
SCHED_MONITOR_LAST = monitors['monitor']
SCHED_VERSION_LAST = monitors['version']
SCHED_RSS_LAST = monitors['rss']
# Start our scheduled background tasks
if UPDATER_STATUS != 'Paused':
SCHED.add_job(func=updater.dbUpdate, id='dbupdater', name='DB Updater', args=[None,None,True], trigger=IntervalTrigger(hours=0, minutes=5, timezone='UTC'))
logger.info('DB Updater sccheduled to fire every 5 minutes')
#let's do a run at the Wanted issues here (on startup) if enabled.
if SEARCH_STATUS != 'Paused':
ss = searchit.CurrentSearcher()
if CONFIG.NZB_STARTUP_SEARCH:
SCHED.add_job(func=ss.run, id='search', next_run_time=datetime.datetime.utcnow(), name='Auto-Search', trigger=IntervalTrigger(hours=0, minutes=CONFIG.SEARCH_INTERVAL, timezone='UTC'))
else:
if SCHED_SEARCH_LAST is not None:
search_timestamp = float(SCHED_SEARCH_LAST)
logger.fdebug('[AUTO-SEARCH] Search last run @ %s' % datetime.datetime.utcfromtimestamp(search_timestamp))
else:
search_timestamp = helpers.utctimestamp() + (int(CONFIG.SEARCH_INTERVAL) *60)
duration_diff = (helpers.utctimestamp() - search_timestamp)/60
if duration_diff >= int(CONFIG.SEARCH_INTERVAL):
logger.fdebug('[AUTO-SEARCH]Auto-Search set to a delay of one minute before initialization as it has been %s minutes since the last run' % duration_diff)
SCHED.add_job(func=ss.run, id='search', name='Auto-Search', trigger=IntervalTrigger(hours=0, minutes=CONFIG.SEARCH_INTERVAL, timezone='UTC'))
else:
search_diff = datetime.datetime.utcfromtimestamp(helpers.utctimestamp() + ((int(CONFIG.SEARCH_INTERVAL) * 60) - (duration_diff*60)))
logger.fdebug('[AUTO-SEARCH] Scheduling next run @ %s every %s minutes' % (search_diff, CONFIG.SEARCH_INTERVAL))
SCHED.add_job(func=ss.run, id='search', name='Auto-Search', next_run_time=search_diff, trigger=IntervalTrigger(hours=0, minutes=CONFIG.SEARCH_INTERVAL, timezone='UTC'))
else:
ss = searchit.CurrentSearcher()
SCHED.add_job(func=ss.run, id='search', name='Auto-Search', next_run_time=None, trigger=IntervalTrigger(hours=0, minutes=CONFIG.SEARCH_INTERVAL, timezone='UTC'))
#thread queue control..
queue_schedule('search_queue', 'start')
if all([CONFIG.ENABLE_TORRENTS, CONFIG.AUTO_SNATCH, OS_DETECT != 'Windows']) and any([CONFIG.TORRENT_DOWNLOADER == 2, CONFIG.TORRENT_DOWNLOADER == 4]):
queue_schedule('snatched_queue', 'start')
if CONFIG.POST_PROCESSING is True and ( all([CONFIG.NZB_DOWNLOADER == 0, CONFIG.SAB_CLIENT_POST_PROCESSING is True]) or all([CONFIG.NZB_DOWNLOADER == 1, CONFIG.NZBGET_CLIENT_POST_PROCESSING is True]) ):
queue_schedule('nzb_queue', 'start')
if CONFIG.POST_PROCESSING is True:
queue_schedule('pp_queue', 'start')
if CONFIG.ENABLE_DDL is True:
queue_schedule('ddl_queue', 'start')
helpers.latestdate_fix()
if CONFIG.ALT_PULL == 2:
weektimer = 4
else:
weektimer = 24
#weekly pull list gets messed up if it's not populated first, so let's populate it then set the scheduler.
logger.info('[WEEKLY] Checking for existance of Weekly Comic listing...')
#now the scheduler (check every 24 hours)
weekly_interval = weektimer * 60 * 60
try:
if SCHED_WEEKLY_LAST:
pass
except:
SCHED_WEEKLY_LAST = None
weektimestamp = helpers.utctimestamp()
if SCHED_WEEKLY_LAST is not None:
weekly_timestamp = float(SCHED_WEEKLY_LAST)
else:
weekly_timestamp = weektimestamp + weekly_interval
ws = weeklypullit.Weekly()
duration_diff = (weektimestamp - weekly_timestamp)/60
if WEEKLY_STATUS != 'Paused':
if abs(duration_diff) >= weekly_interval/60:
logger.info('[WEEKLY] Weekly Pull-Update initializing immediately as it has been %s hours since the last run' % abs(duration_diff/60))
SCHED.add_job(func=ws.run, id='weekly', name='Weekly Pullist', next_run_time=datetime.datetime.utcnow(), trigger=IntervalTrigger(hours=weektimer, minutes=0, timezone='UTC'))
else:
weekly_diff = datetime.datetime.utcfromtimestamp(weektimestamp + (weekly_interval - (duration_diff * 60)))
logger.fdebug('[WEEKLY] Scheduling next run for @ %s every %s hours' % (weekly_diff, weektimer))
SCHED.add_job(func=ws.run, id='weekly', name='Weekly Pullist', next_run_time=weekly_diff, trigger=IntervalTrigger(hours=weektimer, minutes=0, timezone='UTC'))
#initiate startup rss feeds for torrents/nzbs here...
rs = rsscheckit.tehMain()
if CONFIG.ENABLE_RSS is True:
logger.info('[RSS-FEEDS] Initiating startup-RSS feed checks.')
if SCHED_RSS_LAST is not None:
rss_timestamp = float(SCHED_RSS_LAST)
logger.info('[RSS-FEEDS] RSS last run @ %s' % datetime.datetime.utcfromtimestamp(rss_timestamp))
else:
rss_timestamp = helpers.utctimestamp() + (int(CONFIG.RSS_CHECKINTERVAL) *60)
duration_diff = (helpers.utctimestamp() - rss_timestamp)/60
if duration_diff >= int(CONFIG.RSS_CHECKINTERVAL):
SCHED.add_job(func=rs.run, id='rss', name='RSS Feeds', args=[True], next_run_time=datetime.datetime.utcnow(), trigger=IntervalTrigger(hours=0, minutes=int(CONFIG.RSS_CHECKINTERVAL), timezone='UTC'))
else:
rss_diff = datetime.datetime.utcfromtimestamp(helpers.utctimestamp() + (int(CONFIG.RSS_CHECKINTERVAL) * 60) - (duration_diff * 60))
logger.fdebug('[RSS-FEEDS] Scheduling next run for @ %s every %s minutes' % (rss_diff, CONFIG.RSS_CHECKINTERVAL))
SCHED.add_job(func=rs.run, id='rss', name='RSS Feeds', args=[True], next_run_time=rss_diff, trigger=IntervalTrigger(hours=0, minutes=int(CONFIG.RSS_CHECKINTERVAL), timezone='UTC'))
else:
RSS_STATUS = 'Paused'
# SCHED.add_job(func=rs.run, id='rss', name='RSS Feeds', args=[True], trigger=IntervalTrigger(hours=0, minutes=int(CONFIG.RSS_CHECKINTERVAL), timezone='UTC'))
# SCHED.pause_job('rss')
if CONFIG.CHECK_GITHUB:
vs = versioncheckit.CheckVersion()
SCHED.add_job(func=vs.run, id='version', name='Check Version', trigger=IntervalTrigger(hours=0, minutes=CONFIG.CHECK_GITHUB_INTERVAL, timezone='UTC'))
else:
VERSION_STATUS = 'Paused'
##run checkFolder every X minutes (basically Manual Run Post-Processing)
if CONFIG.ENABLE_CHECK_FOLDER:
if CONFIG.DOWNLOAD_SCAN_INTERVAL >0:
logger.info('[FOLDER MONITOR] Enabling folder monitor for : ' + str(CONFIG.CHECK_FOLDER) + ' every ' + str(CONFIG.DOWNLOAD_SCAN_INTERVAL) + ' minutes.')
fm = PostProcessor.FolderCheck()
SCHED.add_job(func=fm.run, id='monitor', name='Folder Monitor', trigger=IntervalTrigger(hours=0, minutes=int(CONFIG.DOWNLOAD_SCAN_INTERVAL), timezone='UTC'))
else:
logger.error('[FOLDER MONITOR] You need to specify a monitoring time for the check folder option to work')
else:
MONITOR_STATUS = 'Paused'
logger.info('Firing up the Background Schedulers now....')
try:
SCHED.start()
#update the job db here
logger.info('Background Schedulers successfully started...')
helpers.job_management(write=True)
except Exception as e:
logger.info(e)
SCHED.print_jobs()
started = True
def queue_schedule(queuetype, mode):
#global _INITIALIZED
if mode == 'start':
if queuetype == 'snatched_queue':
try:
if mylar.SNPOOL.isAlive() is True:
return
except Exception as e:
pass
logger.info('[AUTO-SNATCHER] Auto-Snatch of completed torrents enabled & attempting to background load....')
mylar.SNPOOL = threading.Thread(target=helpers.worker_main, args=(SNATCHED_QUEUE,), name="AUTO-SNATCHER")
mylar.SNPOOL.start()
logger.info('[AUTO-SNATCHER] Succesfully started Auto-Snatch add-on - will now monitor for completed torrents on client....')
elif queuetype == 'nzb_queue':
try:
if mylar.NZBPOOL.isAlive() is True:
return
except Exception as e:
pass
if CONFIG.NZB_DOWNLOADER == 0:
logger.info('[SAB-MONITOR] Completed post-processing handling enabled for SABnzbd. Attempting to background load....')
elif CONFIG.NZB_DOWNLOADER == 1:
logger.info('[NZBGET-MONITOR] Completed post-processing handling enabled for NZBGet. Attempting to background load....')
mylar.NZBPOOL = threading.Thread(target=helpers.nzb_monitor, args=(NZB_QUEUE,), name="AUTO-COMPLETE-NZB")
mylar.NZBPOOL.start()
if CONFIG.NZB_DOWNLOADER == 0:
logger.info('[AUTO-COMPLETE-NZB] Succesfully started Completed post-processing handling for SABnzbd - will now monitor for completed nzbs within sabnzbd and post-process automatically...')
elif CONFIG.NZB_DOWNLOADER == 1:
logger.info('[AUTO-COMPLETE-NZB] Succesfully started Completed post-processing handling for NZBGet - will now monitor for completed nzbs within nzbget and post-process automatically...')
elif queuetype == 'search_queue':
try:
if mylar.SEARCHPOOL.isAlive() is True:
return
except Exception as e:
pass
logger.info('[SEARCH-QUEUE] Attempting to background load the search queue....')
mylar.SEARCHPOOL = threading.Thread(target=helpers.search_queue, args=(SEARCH_QUEUE,), name="SEARCH-QUEUE")
mylar.SEARCHPOOL.start()
logger.info('[SEARCH-QUEUE] Successfully started the Search Queuer...')
elif queuetype == 'pp_queue':
try:
if mylar.PPPOOL.isAlive() is True:
return
except Exception as e:
pass
logger.info('[POST-PROCESS-QUEUE] Post Process queue enabled & monitoring for api requests....')
mylar.PPPOOL = threading.Thread(target=helpers.postprocess_main, args=(PP_QUEUE,), name="POST-PROCESS-QUEUE")
mylar.PPPOOL.start()
logger.info('[POST-PROCESS-QUEUE] Succesfully started Post-Processing Queuer....')
elif queuetype == 'ddl_queue':
try:
if mylar.DDLPOOL.isAlive() is True:
return
except Exception as e:
pass
logger.info('[DDL-QUEUE] DDL Download queue enabled & monitoring for requests....')
mylar.DDLPOOL = threading.Thread(target=helpers.ddl_downloader, args=(DDL_QUEUE,), name="DDL-QUEUE")
mylar.DDLPOOL.start()
logger.info('[DDL-QUEUE:] Succesfully started DDL Download Queuer....')
else:
if (queuetype == 'nzb_queue') or mode == 'shutdown':
try:
if mylar.NZBPOOL.isAlive() is False:
return
elif all([mode!= 'shutdown', mylar.CONFIG.POST_PROCESSING is True]) and ( all([mylar.CONFIG.NZB_DOWNLOADER == 0, mylar.CONFIG.SAB_CLIENT_POST_PROCESSING is True]) or all([mylar.CONFIG.NZB_DOWNLOADER == 1, mylar.CONFIG.NZBGET_CLIENT_POST_PROCESSING is True]) ):
return
except Exception as e:
return
logger.fdebug('Terminating the NZB auto-complete queue thread')
try:
mylar.NZB_QUEUE.put('exit')
mylar.NZBPOOL.join(5)
logger.fdebug('Joined pool for termination - successful')
except KeyboardInterrupt:
mylar.NZB_QUEUE.put('exit')
mylar.NZBPOOL.join(5)
except AssertionError:
if mode == 'shutdown':
os._exit(0)
if (queuetype == 'snatched_queue') or mode == 'shutdown':
try:
if mylar.SNPOOL.isAlive() is False:
return
elif all([mode != 'shutdown', mylar.CONFIG.ENABLE_TORRENTS is True, mylar.CONFIG.AUTO_SNATCH is True, OS_DETECT != 'Windows']) and any([mylar.CONFIG.TORRENT_DOWNLOADER == 2, mylar.CONFIG.TORRENT_DOWNLOADER == 4]):
return
except Exception as e:
return
logger.fdebug('Terminating the auto-snatch thread.')
try:
mylar.SNATCHED_QUEUE.put('exit')
mylar.SNPOOL.join(5)
logger.fdebug('Joined pool for termination - successful')
except KeyboardInterrupt:
mylar.SNATCHED_QUEUE.put('exit')
mylar.SNPOOL.join(5)
except AssertionError:
if mode == 'shutdown':
os._exit(0)
if (queuetype == 'search_queue') or mode == 'shutdown':
try:
if mylar.SEARCHPOOL.isAlive() is False:
return
except Exception as e:
return
logger.fdebug('Terminating the search queue thread.')
try:
mylar.SEARCH_QUEUE.put('exit')
mylar.SEARCHPOOL.join(5)
logger.fdebug('Joined pool for termination - successful')
except KeyboardInterrupt:
mylar.SEARCH_QUEUE.put('exit')
mylar.SEARCHPOOL.join(5)
except AssertionError:
if mode == 'shutdown':
os._exit(0)
if (queuetype == 'pp_queue') or mode == 'shutdown':
try:
if mylar.PPPOOL.isAlive() is False:
return
elif all([mylar.CONFIG.POST_PROCESSING is True, mode != 'shutdown']):
return
except Exception as e:
return
logger.fdebug('Terminating the post-processing queue thread.')
try:
mylar.PP_QUEUE.put('exit')
mylar.PPPOOL.join(5)
logger.fdebug('Joined pool for termination - successful')
except KeyboardInterrupt:
mylar.PP_QUEUE.put('exit')
mylar.PPPOOL.join(5)
except AssertionError:
if mode == 'shutdown':
os._exit(0)
if (queuetype == 'ddl_queue') or mode == 'shutdown':
try:
if mylar.DDLPOOL.isAlive() is False:
return
elif all([mylar.CONFIG.ENABLE_DDL is True, mode != 'shutdown']):
return
except Exception as e:
return
logger.fdebug('Terminating the DDL download queue thread')
try:
mylar.DDL_QUEUE.put('exit')
mylar.DDLPOOL.join(5)
logger.fdebug('Joined pool for termination - successful')
except KeyboardInterrupt:
mylar.DDL_QUEUE.put('exit')
DDLPOOL.join(5)
except AssertionError:
if mode == 'shutdown':
os._exit(0)
def dbcheck():
conn = sqlite3.connect(DB_FILE)
c_error = 'sqlite3.OperationalError'
c=conn.cursor()
try:
c.execute('SELECT ReleaseDate from storyarcs')
except sqlite3.OperationalError:
try:
c.execute('CREATE TABLE IF NOT EXISTS storyarcs(StoryArcID TEXT, ComicName TEXT, IssueNumber TEXT, SeriesYear TEXT, IssueYEAR TEXT, StoryArc TEXT, TotalIssues TEXT, Status TEXT, inCacheDir TEXT, Location TEXT, IssueArcID TEXT, ReadingOrder INT, IssueID TEXT, ComicID TEXT, ReleaseDate TEXT, IssueDate TEXT, Publisher TEXT, IssuePublisher TEXT, IssueName TEXT, CV_ArcID TEXT, Int_IssueNumber INT, DynamicComicName TEXT, Volume TEXT, Manual TEXT, DateAdded TEXT, DigitalDate TEXT, Type TEXT, Aliases TEXT)')
c.execute('INSERT INTO storyarcs(StoryArcID, ComicName, IssueNumber, SeriesYear, IssueYEAR, StoryArc, TotalIssues, Status, inCacheDir, Location, IssueArcID, ReadingOrder, IssueID, ComicID, ReleaseDate, IssueDate, Publisher, IssuePublisher, IssueName, CV_ArcID, Int_IssueNumber, DynamicComicName, Volume, Manual) SELECT StoryArcID, ComicName, IssueNumber, SeriesYear, IssueYEAR, StoryArc, TotalIssues, Status, inCacheDir, Location, IssueArcID, ReadingOrder, IssueID, ComicID, StoreDate, IssueDate, Publisher, IssuePublisher, IssueName, CV_ArcID, Int_IssueNumber, DynamicComicName, Volume, Manual FROM readinglist')
c.execute('DROP TABLE readinglist')
except sqlite3.OperationalError:
logger.warn('Unable to update readinglist table to new storyarc table format.')
c.execute('CREATE TABLE IF NOT EXISTS comics (ComicID TEXT UNIQUE, ComicName TEXT, ComicSortName TEXT, ComicYear TEXT, DateAdded TEXT, Status TEXT, IncludeExtras INTEGER, Have INTEGER, Total INTEGER, ComicImage TEXT, ComicPublisher TEXT, ComicLocation TEXT, ComicPublished TEXT, NewPublish TEXT, LatestIssue TEXT, LatestDate TEXT, Description TEXT, QUALalt_vers TEXT, QUALtype TEXT, QUALscanner TEXT, QUALquality TEXT, LastUpdated TEXT, AlternateSearch TEXT, UseFuzzy TEXT, ComicVersion TEXT, SortOrder INTEGER, DetailURL TEXT, ForceContinuing INTEGER, ComicName_Filesafe TEXT, AlternateFileName TEXT, ComicImageURL TEXT, ComicImageALTURL TEXT, DynamicComicName TEXT, AllowPacks TEXT, Type TEXT, Corrected_SeriesYear TEXT, Corrected_Type TEXT, TorrentID_32P TEXT, LatestIssueID TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS issues (IssueID TEXT, ComicName TEXT, IssueName TEXT, Issue_Number TEXT, DateAdded TEXT, Status TEXT, Type TEXT, ComicID TEXT, ArtworkURL Text, ReleaseDate TEXT, Location TEXT, IssueDate TEXT, DigitalDate TEXT, Int_IssueNumber INT, ComicSize TEXT, AltIssueNumber TEXT, IssueDate_Edit TEXT, ImageURL TEXT, ImageURL_ALT TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS snatched (IssueID TEXT, ComicName TEXT, Issue_Number TEXT, Size INTEGER, DateAdded TEXT, Status TEXT, FolderName TEXT, ComicID TEXT, Provider TEXT, Hash TEXT, crc TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS upcoming (ComicName TEXT, IssueNumber TEXT, ComicID TEXT, IssueID TEXT, IssueDate TEXT, Status TEXT, DisplayComicName TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS nzblog (IssueID TEXT, NZBName TEXT, SARC TEXT, PROVIDER TEXT, ID TEXT, AltNZBName TEXT, OneOff TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS weekly (SHIPDATE TEXT, PUBLISHER TEXT, ISSUE TEXT, COMIC VARCHAR(150), EXTRA TEXT, STATUS TEXT, ComicID TEXT, IssueID TEXT, CV_Last_Update TEXT, DynamicName TEXT, weeknumber TEXT, year TEXT, volume TEXT, seriesyear TEXT, annuallink TEXT, format TEXT, rowid INTEGER PRIMARY KEY)')
c.execute('CREATE TABLE IF NOT EXISTS importresults (impID TEXT, ComicName TEXT, ComicYear TEXT, Status TEXT, ImportDate TEXT, ComicFilename TEXT, ComicLocation TEXT, WatchMatch TEXT, DisplayName TEXT, SRID TEXT, ComicID TEXT, IssueID TEXT, Volume TEXT, IssueNumber TEXT, DynamicName TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS readlist (IssueID TEXT, ComicName TEXT, Issue_Number TEXT, Status TEXT, DateAdded TEXT, Location TEXT, inCacheDir TEXT, SeriesYear TEXT, ComicID TEXT, StatusChange TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS annuals (IssueID TEXT, Issue_Number TEXT, IssueName TEXT, IssueDate TEXT, Status TEXT, ComicID TEXT, GCDComicID TEXT, Location TEXT, ComicSize TEXT, Int_IssueNumber INT, ComicName TEXT, ReleaseDate TEXT, DigitalDate TEXT, ReleaseComicID TEXT, ReleaseComicName TEXT, IssueDate_Edit TEXT, DateAdded TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS rssdb (Title TEXT UNIQUE, Link TEXT, Pubdate TEXT, Site TEXT, Size TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS futureupcoming (ComicName TEXT, IssueNumber TEXT, ComicID TEXT, IssueID TEXT, IssueDate TEXT, Publisher TEXT, Status TEXT, DisplayComicName TEXT, weeknumber TEXT, year TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS failed (ID TEXT, Status TEXT, ComicID TEXT, IssueID TEXT, Provider TEXT, ComicName TEXT, Issue_Number TEXT, NZBName TEXT, DateFailed TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS searchresults (SRID TEXT, results Numeric, Series TEXT, publisher TEXT, haveit TEXT, name TEXT, deck TEXT, url TEXT, description TEXT, comicid TEXT, comicimage TEXT, issues TEXT, comicyear TEXT, ogcname TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS ref32p (ComicID TEXT UNIQUE, ID TEXT, Series TEXT, Updated TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS oneoffhistory (ComicName TEXT, IssueNumber TEXT, ComicID TEXT, IssueID TEXT, Status TEXT, weeknumber TEXT, year TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS jobhistory (JobName TEXT, prev_run_datetime timestamp, prev_run_timestamp REAL, next_run_datetime timestamp, next_run_timestamp REAL, last_run_completed TEXT, successful_completions TEXT, failed_completions TEXT, status TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS manualresults (provider TEXT, id TEXT, kind TEXT, comicname TEXT, volume TEXT, oneoff TEXT, fullprov TEXT, issuenumber TEXT, modcomicname TEXT, name TEXT, link TEXT, size TEXT, pack_numbers TEXT, pack_issuelist TEXT, comicyear TEXT, issuedate TEXT, tmpprov TEXT, pack TEXT, issueid TEXT, comicid TEXT, sarc TEXT, issuearcid TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS storyarcs(StoryArcID TEXT, ComicName TEXT, IssueNumber TEXT, SeriesYear TEXT, IssueYEAR TEXT, StoryArc TEXT, TotalIssues TEXT, Status TEXT, inCacheDir TEXT, Location TEXT, IssueArcID TEXT, ReadingOrder INT, IssueID TEXT, ComicID TEXT, ReleaseDate TEXT, IssueDate TEXT, Publisher TEXT, IssuePublisher TEXT, IssueName TEXT, CV_ArcID TEXT, Int_IssueNumber INT, DynamicComicName TEXT, Volume TEXT, Manual TEXT, DateAdded TEXT, DigitalDate TEXT, Type TEXT, Aliases TEXT)')
c.execute('CREATE TABLE IF NOT EXISTS ddl_info (ID TEXT UNIQUE, series TEXT, year TEXT, filename TEXT, size TEXT, issueid TEXT, comicid TEXT, link TEXT, status TEXT, remote_filesize TEXT, updated_date TEXT, mainlink TEXT, issues TEXT)')
conn.commit
c.close
csv_load()
#add in the late players to the game....
# -- Comics Table --
try:
c.execute('SELECT LastUpdated from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN LastUpdated TEXT')
try:
c.execute('SELECT QUALalt_vers from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN QUALalt_vers TEXT')
try:
c.execute('SELECT QUALtype from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN QUALtype TEXT')
try:
c.execute('SELECT QUALscanner from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN QUALscanner TEXT')
try:
c.execute('SELECT QUALquality from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN QUALquality TEXT')
try:
c.execute('SELECT AlternateSearch from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN AlternateSearch TEXT')
try:
c.execute('SELECT ComicVersion from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN ComicVersion TEXT')
try:
c.execute('SELECT SortOrder from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN SortOrder INTEGER')
try:
c.execute('SELECT UseFuzzy from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN UseFuzzy TEXT')
try:
c.execute('SELECT DetailURL from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN DetailURL TEXT')
try:
c.execute('SELECT ForceContinuing from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN ForceContinuing INTEGER')
try:
c.execute('SELECT ComicName_Filesafe from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN ComicName_Filesafe TEXT')
try:
c.execute('SELECT AlternateFileName from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN AlternateFileName TEXT')
try:
c.execute('SELECT ComicImageURL from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN ComicImageURL TEXT')
try:
c.execute('SELECT ComicImageALTURL from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN ComicImageALTURL TEXT')
try:
c.execute('SELECT NewPublish from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN NewPublish TEXT')
try:
c.execute('SELECT AllowPacks from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN AllowPacks TEXT')
try:
c.execute('SELECT Type from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN Type TEXT')
try:
c.execute('SELECT Corrected_SeriesYear from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN Corrected_SeriesYear TEXT')
try:
c.execute('SELECT Corrected_Type from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN Corrected_Type TEXT')
try:
c.execute('SELECT TorrentID_32P from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN TorrentID_32P TEXT')
try:
c.execute('SELECT LatestIssueID from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN LatestIssueID TEXT')
try:
c.execute('SELECT Collects from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN Collects CLOB')
try:
c.execute('SELECT DynamicComicName from comics')
if CONFIG.DYNAMIC_UPDATE < 3:
dynamic_upgrade = True
else:
dynamic_upgrade = False
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN DynamicComicName TEXT')
dynamic_upgrade = True
# -- Issues Table --
try:
c.execute('SELECT ComicSize from issues')
except sqlite3.OperationalError:
c.execute('ALTER TABLE issues ADD COLUMN ComicSize TEXT')
try:
c.execute('SELECT inCacheDir from issues')
except sqlite3.OperationalError:
c.execute('ALTER TABLE issues ADD COLUMN inCacheDIR TEXT')
try:
c.execute('SELECT AltIssueNumber from issues')
except sqlite3.OperationalError:
c.execute('ALTER TABLE issues ADD COLUMN AltIssueNumber TEXT')
try:
c.execute('SELECT IssueDate_Edit from issues')
except sqlite3.OperationalError:
c.execute('ALTER TABLE issues ADD COLUMN IssueDate_Edit TEXT')
try:
c.execute('SELECT ImageURL from issues')
except sqlite3.OperationalError:
c.execute('ALTER TABLE issues ADD COLUMN ImageURL TEXT')
try:
c.execute('SELECT ImageURL_ALT from issues')
except sqlite3.OperationalError:
c.execute('ALTER TABLE issues ADD COLUMN ImageURL_ALT TEXT')
try:
c.execute('SELECT DigitalDate from issues')
except sqlite3.OperationalError:
c.execute('ALTER TABLE issues ADD COLUMN DigitalDate TEXT')
## -- ImportResults Table --
try:
c.execute('SELECT WatchMatch from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN WatchMatch TEXT')
try:
c.execute('SELECT IssueCount from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN IssueCount TEXT')
try:
c.execute('SELECT ComicLocation from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN ComicLocation TEXT')
try:
c.execute('SELECT ComicFilename from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN ComicFilename TEXT')
try:
c.execute('SELECT impID from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN impID TEXT')
try:
c.execute('SELECT implog from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN implog TEXT')
try:
c.execute('SELECT DisplayName from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN DisplayName TEXT')
try:
c.execute('SELECT SRID from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN SRID TEXT')
try:
c.execute('SELECT ComicID from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN ComicID TEXT')
try:
c.execute('SELECT IssueID from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN IssueID TEXT')
try:
c.execute('SELECT Volume from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN Volume TEXT')
try:
c.execute('SELECT IssueNumber from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN IssueNumber TEXT')
try:
c.execute('SELECT DynamicName from importresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE importresults ADD COLUMN DynamicName TEXT')
## -- Readlist Table --
try:
c.execute('SELECT inCacheDIR from readlist')
except sqlite3.OperationalError:
c.execute('ALTER TABLE readlist ADD COLUMN inCacheDIR TEXT')
try:
c.execute('SELECT Location from readlist')
except sqlite3.OperationalError:
c.execute('ALTER TABLE readlist ADD COLUMN Location TEXT')
try:
c.execute('SELECT IssueDate from readlist')
except sqlite3.OperationalError:
c.execute('ALTER TABLE readlist ADD COLUMN IssueDate TEXT')
try:
c.execute('SELECT SeriesYear from readlist')
except sqlite3.OperationalError:
c.execute('ALTER TABLE readlist ADD COLUMN SeriesYear TEXT')
try:
c.execute('SELECT ComicID from readlist')
except sqlite3.OperationalError:
c.execute('ALTER TABLE readlist ADD COLUMN ComicID TEXT')
try:
c.execute('SELECT StatusChange from readlist')
except sqlite3.OperationalError:
c.execute('ALTER TABLE readlist ADD COLUMN StatusChange TEXT')
## -- Weekly Table --
try:
c.execute('SELECT ComicID from weekly')
except sqlite3.OperationalError:
c.execute('ALTER TABLE weekly ADD COLUMN ComicID TEXT')
try:
c.execute('SELECT IssueID from weekly')
except sqlite3.OperationalError:
c.execute('ALTER TABLE weekly ADD COLUMN IssueID TEXT')
try:
c.execute('SELECT DynamicName from weekly')
except sqlite3.OperationalError:
c.execute('ALTER TABLE weekly ADD COLUMN DynamicName TEXT')
try:
c.execute('SELECT CV_Last_Update from weekly')
except sqlite3.OperationalError:
c.execute('ALTER TABLE weekly ADD COLUMN CV_Last_Update TEXT')
try:
c.execute('SELECT weeknumber from weekly')
except sqlite3.OperationalError:
c.execute('ALTER TABLE weekly ADD COLUMN weeknumber TEXT')
try:
c.execute('SELECT year from weekly')
except sqlite3.OperationalError:
c.execute('ALTER TABLE weekly ADD COLUMN year TEXT')
try:
c.execute('SELECT rowid from weekly')
except sqlite3.OperationalError:
c.execute('ALTER TABLE weekly ADD COLUMN rowid INTEGER PRIMARY KEY')
try:
c.execute('SELECT volume from weekly')
except sqlite3.OperationalError:
c.execute('ALTER TABLE weekly ADD COLUMN volume TEXT')
try:
c.execute('SELECT seriesyear from weekly')
except sqlite3.OperationalError:
c.execute('ALTER TABLE weekly ADD COLUMN seriesyear TEXT')
try:
c.execute('SELECT annuallink from weekly')
except sqlite3.OperationalError:
c.execute('ALTER TABLE weekly ADD COLUMN annuallink TEXT')
try:
c.execute('SELECT format from weekly')
except sqlite3.OperationalError:
c.execute('ALTER TABLE weekly ADD COLUMN format TEXT')
## -- Nzblog Table --
try:
c.execute('SELECT SARC from nzblog')
except sqlite3.OperationalError:
c.execute('ALTER TABLE nzblog ADD COLUMN SARC TEXT')
try:
c.execute('SELECT PROVIDER from nzblog')
except sqlite3.OperationalError:
c.execute('ALTER TABLE nzblog ADD COLUMN PROVIDER TEXT')
try:
c.execute('SELECT ID from nzblog')
except sqlite3.OperationalError:
c.execute('ALTER TABLE nzblog ADD COLUMN ID TEXT')
try:
c.execute('SELECT AltNZBName from nzblog')
except sqlite3.OperationalError:
c.execute('ALTER TABLE nzblog ADD COLUMN AltNZBName TEXT')
try:
c.execute('SELECT OneOff from nzblog')
except sqlite3.OperationalError:
c.execute('ALTER TABLE nzblog ADD COLUMN OneOff TEXT')
## -- Annuals Table --
try:
c.execute('SELECT Location from annuals')
except sqlite3.OperationalError:
c.execute('ALTER TABLE annuals ADD COLUMN Location TEXT')
try:
c.execute('SELECT ComicSize from annuals')
except sqlite3.OperationalError:
c.execute('ALTER TABLE annuals ADD COLUMN ComicSize TEXT')
try:
c.execute('SELECT Int_IssueNumber from annuals')
except sqlite3.OperationalError:
c.execute('ALTER TABLE annuals ADD COLUMN Int_IssueNumber INT')
try:
c.execute('SELECT ComicName from annuals')
annual_update = "no"
except sqlite3.OperationalError:
c.execute('ALTER TABLE annuals ADD COLUMN ComicName TEXT')
annual_update = "yes"
if annual_update == "yes":
logger.info("Updating Annuals table for new fields - one-time update.")
helpers.annual_update()
try:
c.execute('SELECT ReleaseDate from annuals')
except sqlite3.OperationalError:
c.execute('ALTER TABLE annuals ADD COLUMN ReleaseDate TEXT')
try:
c.execute('SELECT ReleaseComicID from annuals')
except sqlite3.OperationalError:
c.execute('ALTER TABLE annuals ADD COLUMN ReleaseComicID TEXT')
try:
c.execute('SELECT ReleaseComicName from annuals')
except sqlite3.OperationalError:
c.execute('ALTER TABLE annuals ADD COLUMN ReleaseComicName TEXT')
try:
c.execute('SELECT IssueDate_Edit from annuals')
except sqlite3.OperationalError:
c.execute('ALTER TABLE annuals ADD COLUMN IssueDate_Edit TEXT')
try:
c.execute('SELECT DateAdded from annuals')
except sqlite3.OperationalError:
c.execute('ALTER TABLE annuals ADD COLUMN DateAdded TEXT')
try:
c.execute('SELECT DigitalDate from annuals')
except sqlite3.OperationalError:
c.execute('ALTER TABLE annuals ADD COLUMN DigitalDate TEXT')
## -- Snatched Table --
try:
c.execute('SELECT Provider from snatched')
except sqlite3.OperationalError:
c.execute('ALTER TABLE snatched ADD COLUMN Provider TEXT')
try:
c.execute('SELECT Hash from snatched')
except sqlite3.OperationalError:
c.execute('ALTER TABLE snatched ADD COLUMN Hash TEXT')
try:
c.execute('SELECT crc from snatched')
except sqlite3.OperationalError:
c.execute('ALTER TABLE snatched ADD COLUMN crc TEXT')
## -- Upcoming Table --
try:
c.execute('SELECT DisplayComicName from upcoming')
except sqlite3.OperationalError:
c.execute('ALTER TABLE upcoming ADD COLUMN DisplayComicName TEXT')
## -- storyarcs Table --
try:
c.execute('SELECT ComicID from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN ComicID TEXT')
try:
c.execute('SELECT StoreDate from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN StoreDate TEXT')
try:
c.execute('SELECT IssueDate from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN IssueDate TEXT')
try:
c.execute('SELECT Publisher from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN Publisher TEXT')
try:
c.execute('SELECT IssuePublisher from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN IssuePublisher TEXT')
try:
c.execute('SELECT IssueName from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN IssueName TEXT')
try:
c.execute('SELECT CV_ArcID from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN CV_ArcID TEXT')
try:
c.execute('SELECT Int_IssueNumber from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN Int_IssueNumber INT')
try:
c.execute('SELECT DynamicComicName from storyarcs')
if CONFIG.DYNAMIC_UPDATE < 4:
dynamic_upgrade = True
else:
dynamic_upgrade = False
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN DynamicComicName TEXT')
dynamic_upgrade = True
try:
c.execute('SELECT Volume from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN Volume TEXT')
try:
c.execute('SELECT Manual from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN Manual TEXT')
try:
c.execute('SELECT DateAdded from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN DateAdded TEXT')
try:
c.execute('SELECT DigitalDate from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN DigitalDate TEXT')
try:
c.execute('SELECT Type from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN Type TEXT')
try:
c.execute('SELECT Aliases from storyarcs')
except sqlite3.OperationalError:
c.execute('ALTER TABLE storyarcs ADD COLUMN Aliases TEXT')
## -- searchresults Table --
try:
c.execute('SELECT SRID from searchresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE searchresults ADD COLUMN SRID TEXT')
try:
c.execute('SELECT Series from searchresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE searchresults ADD COLUMN Series TEXT')
try:
c.execute('SELECT sresults from searchresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE searchresults ADD COLUMN sresults TEXT')
try:
c.execute('SELECT ogcname from searchresults')
except sqlite3.OperationalError:
c.execute('ALTER TABLE searchresults ADD COLUMN ogcname TEXT')
## -- futureupcoming Table --
try:
c.execute('SELECT weeknumber from futureupcoming')
except sqlite3.OperationalError:
c.execute('ALTER TABLE futureupcoming ADD COLUMN weeknumber TEXT')
try:
c.execute('SELECT year from futureupcoming')
except sqlite3.OperationalError:
c.execute('ALTER TABLE futureupcoming ADD COLUMN year TEXT')
## -- Failed Table --
try:
c.execute('SELECT DateFailed from Failed')
except sqlite3.OperationalError:
c.execute('ALTER TABLE Failed ADD COLUMN DateFailed TEXT')
## -- Ref32p Table --
try:
c.execute('SELECT Updated from ref32p')
except sqlite3.OperationalError:
c.execute('ALTER TABLE ref32p ADD COLUMN Updated TEXT')
## -- Jobhistory Table --
try:
c.execute('SELECT status from jobhistory')
except sqlite3.OperationalError:
c.execute('ALTER TABLE jobhistory ADD COLUMN status TEXT')
## -- DDL_info Table --
try:
c.execute('SELECT remote_filesize from ddl_info')
except sqlite3.OperationalError:
c.execute('ALTER TABLE ddl_info ADD COLUMN remote_filesize TEXT')
try:
c.execute('SELECT updated_date from ddl_info')
except sqlite3.OperationalError:
c.execute('ALTER TABLE ddl_info ADD COLUMN updated_date TEXT')
try:
c.execute('SELECT mainlink from ddl_info')
except sqlite3.OperationalError:
c.execute('ALTER TABLE ddl_info ADD COLUMN mainlink TEXT')
try:
c.execute('SELECT issues from ddl_info')
except sqlite3.OperationalError:
c.execute('ALTER TABLE ddl_info ADD COLUMN issues TEXT')
#if it's prior to Wednesday, the issue counts will be inflated by one as the online db's everywhere
#prepare for the next 'new' release of a series. It's caught in updater.py, so let's just store the
#value in the sql so we can display it in the details screen for everyone to wonder at.
try:
c.execute('SELECT not_updated_db from comics')
except sqlite3.OperationalError:
c.execute('ALTER TABLE comics ADD COLUMN not_updated_db TEXT')
# -- not implemented just yet ;)
# for metadata...
# MetaData_Present will be true/false if metadata is present
# MetaData will hold the MetaData itself in tuple format
# try:
# c.execute('SELECT MetaData_Present from comics')
# except sqlite3.OperationalError:
# c.execute('ALTER TABLE importresults ADD COLUMN MetaData_Present TEXT')
# try:
# c.execute('SELECT MetaData from importresults')
# except sqlite3.OperationalError:
# c.execute('ALTER TABLE importresults ADD COLUMN MetaData TEXT')
#let's delete errant comics that are stranded (ie. Comicname = Comic ID: )
c.execute("DELETE from comics WHERE ComicName='None' OR ComicName LIKE 'Comic ID%' OR ComicName is NULL")
c.execute("DELETE from issues WHERE ComicName='None' OR ComicName LIKE 'Comic ID%' OR ComicName is NULL")
c.execute("DELETE from issues WHERE ComicID is NULL")
c.execute("DELETE from annuals WHERE ComicName='None' OR ComicName is NULL or Issue_Number is NULL")
c.execute("DELETE from upcoming WHERE ComicName='None' OR ComicName is NULL or IssueNumber is NULL")
c.execute("DELETE from importresults WHERE ComicName='None' OR ComicName is NULL")
c.execute("DELETE from storyarcs WHERE StoryArcID is NULL OR StoryArc is NULL")
c.execute("DELETE from Failed WHERE ComicName='None' OR ComicName is NULL OR ID is NULL")
logger.info('Ensuring DB integrity - Removing all Erroneous Comics (ie. named None)')
logger.info('Correcting Null entries that make the main page break on startup.')
c.execute("UPDATE Comics SET LatestDate='Unknown' WHERE LatestDate='None' or LatestDate is NULL")
job_listing = c.execute('SELECT * FROM jobhistory')
job_history = []
for jh in job_listing:
job_history.append(jh)
#logger.fdebug('job_history loaded: %s' % job_history)
conn.commit()
c.close()
if dynamic_upgrade is True:
logger.info('Updating db to include some important changes.')
helpers.upgrade_dynamic()
def csv_load():
# for redudant module calls..include this.
conn = sqlite3.connect(DB_FILE)
c=conn.cursor()
c.execute('DROP TABLE IF EXISTS exceptions')
c.execute('CREATE TABLE IF NOT EXISTS exceptions (variloop TEXT, ComicID TEXT, NewComicID TEXT, GComicID TEXT)')
# for Mylar-based Exception Updates....
i = 0
EXCEPTIONS = []
EXCEPTIONS.append('exceptions.csv')
EXCEPTIONS.append('custom_exceptions.csv')
while (i <= 1):
#EXCEPTIONS_FILE = os.path.join(DATA_DIR, 'exceptions.csv')
EXCEPTIONS_FILE = os.path.join(DATA_DIR, EXCEPTIONS[i])
if not os.path.exists(EXCEPTIONS_FILE):
try:
csvfile = open(str(EXCEPTIONS_FILE), "rb")
except (OSError, IOError):
if i == 1:
logger.info('No Custom Exceptions found - Using base exceptions only. Creating blank custom_exceptions for your personal use.')
try:
shutil.copy(os.path.join(DATA_DIR, "custom_exceptions_sample.csv"), EXCEPTIONS_FILE)
except (OSError, IOError):
logger.error('Cannot create custom_exceptions.csv in ' + str(DATA_DIR) + '. Make sure custom_exceptions_sample.csv is present and/or check permissions.')
return
else:
logger.error('Could not locate ' + str(EXCEPTIONS[i]) + ' file. Make sure it is in datadir: ' + DATA_DIR)
break
else:
csvfile = open(str(EXCEPTIONS_FILE), "rb")
if i == 0:
logger.info('Populating Base Exception listings into Mylar....')
elif i == 1:
logger.info('Populating Custom Exception listings into Mylar....')
creader = csv.reader(csvfile, delimiter=',')
for row in creader:
try:
#print row.split(',')
c.execute("INSERT INTO exceptions VALUES (?,?,?,?)", row)
except Exception, e:
#print ("Error - invald arguments...-skipping")
pass
csvfile.close()
i+=1
conn.commit()
c.close()
def halt():
global _INITIALIZED, started
with INIT_LOCK:
if _INITIALIZED:
logger.info('Shutting down the background schedulers...')
SCHED.shutdown(wait=False)
queue_schedule('all', 'shutdown')
#if NZBPOOL is not None:
# queue_schedule('nzb_queue', 'shutdown')
#if SNPOOL is not None:
# queue_schedule('snatched_queue', 'shutdown')
#if SEARCHPOOL is not None:
# queue_schedule('search_queue', 'shutdown')
#if PPPOOL is not None:
# queue_schedule('pp_queue', 'shutdown')
#if DDLPOOL is not None:
# queue_schedule('ddl_queue', 'shutdown')
_INITIALIZED = False
def shutdown(restart=False, update=False, maintenance=False):
if maintenance is False:
cherrypy.engine.exit()
halt()
if not restart and not update:
logger.info('Mylar is shutting down...')
if update:
logger.info('Mylar is updating...')
try:
versioncheck.update()
except Exception as e:
logger.warn('Mylar failed to update: %s. Restarting.' % e)
if CREATEPID:
logger.info('Removing pidfile %s' % PIDFILE)
os.remove(PIDFILE)
if restart:
logger.info('Mylar is restarting...')
popen_list = [sys.executable, FULL_PATH]
if 'maintenance' not in ARGS:
popen_list += ARGS
else:
for x in ARGS:
if all([x != 'maintenance', x != '-u']):
popen_list += x
logger.info('Restarting Mylar with ' + str(popen_list))
subprocess.Popen(popen_list, cwd=os.getcwd())
os._exit(0)
| 60,524 | Python | .py | 1,193 | 41.483655 | 789 | 0.66191 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,254 | scheduler.py | evilhero_mylar/mylar/scheduler.py | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Sick Beard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Sick Beard. If not, see <http://www.gnu.org/licenses/>.
import datetime
import time
import threading
import traceback
from mylar import logger
class Scheduler:
def __init__(self, action, cycleTime=datetime.timedelta(minutes=10), runImmediately=True,
threadName="ScheduledThread", silent=False, delay=None):
if runImmediately:
self.lastRun = datetime.datetime.fromordinal(1)
else:
self.lastRun = datetime.datetime.now()
self.action = action
self.cycleTime = cycleTime
self.thread = None
self.threadName = threadName
self.silent = silent
self.delay = delay
self.initThread()
self.abort = False
def initThread(self):
if self.thread == None or not self.thread.isAlive():
self.thread = threading.Thread(None, self.runAction, self.threadName)
def timeLeft(self):
return self.cycleTime - (datetime.datetime.now() - self.lastRun)
def forceRun(self):
if not self.action.amActive:
self.lastRun = datetime.datetime.fromordinal(1)
return True
return False
def runAction(self):
while True:
currentTime = datetime.datetime.now()
if currentTime - self.lastRun > self.cycleTime:
self.lastRun = currentTime
try:
if not self.silent:
logger.fdebug("Starting new thread: " + self.threadName)
if self.delay:
logger.info('delaying thread for ' + str(self.delay) + ' seconds to avoid locks.')
time.sleep(self.delay)
self.action.run()
except Exception, e:
logger.fdebug("Exception generated in thread " + self.threadName + ": %s" % e)
logger.fdebug(repr(traceback.format_exc()))
if self.abort:
self.abort = False
self.thread = None
return
time.sleep(1)
| 2,776 | Python | .py | 67 | 32.164179 | 106 | 0.630952 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,255 | versioncheckit.py | evilhero_mylar/mylar/versioncheckit.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import mylar
from mylar import logger, helpers, versioncheck
class CheckVersion():
def __init__(self):
pass
def run(self):
logger.info('[VersionCheck] Checking for new release on Github.')
helpers.job_management(write=True, job='Check Version', current_run=helpers.utctimestamp(), status='Running')
mylar.VERSION_STATUS = 'Running'
versioncheck.checkGithub()
helpers.job_management(write=True, job='Check Version', last_run_completed=helpers.utctimestamp(), status='Waiting')
mylar.VERSION_STATUS = 'Waiting'
| 1,261 | Python | .py | 27 | 43.148148 | 124 | 0.74288 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,256 | logger.py | evilhero_mylar/mylar/logger.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import inspect
import traceback
import threading
import platform
import locale
import mylar
from mylar import helpers
import logging
from logging import getLogger, WARN, ERROR, INFO, DEBUG, StreamHandler, Formatter, Handler
from lib.six import PY2
#setup logger for non-english (this doesnt carry thru, so check here too)
try:
localeinfo = locale.getdefaultlocale()
language = localeinfo[0]
charset = localeinfo[1]
if any([language is None, charset is None]):
raise AttributeError
except AttributeError:
#if it's set to None (ie. dockerized) - default to en_US.UTF-8.
if language is None:
language = 'en_US'
if charset is None:
charset = 'UTF-8'
LOG_LANG = language
LOG_CHARSET = charset
if not LOG_LANG.startswith('en'):
# Simple rotating log handler that uses RotatingFileHandler
class RotatingLogger(object):
def __init__(self, filename):
self.filename = filename
self.filehandler = None
self.consolehandler = None
def stopLogger(self):
lg = logging.getLogger('mylar')
lg.removeHandler(self.filehandler)
lg.removeHandler(self.consolehandler)
def handle_exception(self, exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
logger.exception('Uncaught Exception', excinfo=(exc_type, exc_value, exc_traceback))
sys.__excepthook__(exc_type, exc_value, None)
return
def initLogger(self, loglevel=1, log_dir=None, max_logsize=None, max_logfiles=None):
import sys
sys.excepthook = RotatingLogger.handle_exception
logging.getLogger('apscheduler.scheduler').setLevel(logging.WARN)
logging.getLogger('apscheduler.threadpool').setLevel(logging.WARN)
logging.getLogger('apscheduler.scheduler').propagate = False
logging.getLogger('apscheduler.threadpool').propagate = False
logging.getLogger('cherrypy').propagate = False
lg = logging.getLogger('mylar')
lg.setLevel(logging.DEBUG)
if log_dir is not None:
self.filename = os.path.join(log_dir, self.filename)
#concurrentLogHandler/0.8.7 (to deal with windows locks)
#since this only happens on windows boxes, if it's nix/mac use the default logger.
if mylar.OS_DETECT == 'Windows':
#set the path to the lib here - just to make sure it can detect cloghandler & portalocker.
import sys
sys.path.append(os.path.join(mylar.PROG_DIR, 'lib'))
try:
from ConcurrentLogHandler.cloghandler import ConcurrentRotatingFileHandler as RFHandler
mylar.LOGTYPE = 'clog'
except ImportError:
mylar.LOGTYPE = 'log'
from logging.handlers import RotatingFileHandler as RFHandler
else:
mylar.LOGTYPE = 'log'
from logging.handlers import RotatingFileHandler as RFHandler
filehandler = RFHandler(
self.filename,
maxBytes=max_logsize,
backupCount=max_logfiles)
filehandler.setLevel(logging.DEBUG)
fileformatter = logging.Formatter('%(asctime)s - %(levelname)-7s :: %(message)s', '%d-%b-%Y %H:%M:%S')
filehandler.setFormatter(fileformatter)
lg.addHandler(filehandler)
self.filehandler = filehandler
if loglevel:
consolehandler = logging.StreamHandler()
if loglevel == 1:
consolehandler.setLevel(logging.INFO)
if loglevel >= 2:
consolehandler.setLevel(logging.DEBUG)
consoleformatter = logging.Formatter('%(asctime)s - %(levelname)s :: %(message)s', '%d-%b-%Y %H:%M:%S')
consolehandler.setFormatter(consoleformatter)
lg.addHandler(consolehandler)
self.consolehandler = consolehandler
@staticmethod
def log(message, level):
logger = logging.getLogger('mylar')
threadname = threading.currentThread().getName()
# Get the frame data of the method that made the original logger call
if len(inspect.stack()) > 2:
frame = inspect.getframeinfo(inspect.stack()[2][0])
program = os.path.basename(frame.filename)
method = frame.function
lineno = frame.lineno
else:
program = ""
method = ""
lineno = ""
if PY2:
message = safe_unicode(message)
message = message.encode(mylar.SYS_ENCODING)
if level != 'DEBUG' or mylar.LOG_LEVEL >= 2:
mylar.LOGLIST.insert(0, (helpers.now(), message, level, threadname))
if len(mylar.LOGLIST) > 2500:
del mylar.LOGLIST[-1]
message = "%s : %s:%s:%s : %s" % (threadname, program, method, lineno, message)
if level == 'DEBUG':
logger.debug(message)
elif level == 'INFO':
logger.info(message)
elif level == 'WARNING':
logger.warning(message)
else:
logger.error(message)
mylar_log = RotatingLogger('mylar.log')
filename = 'mylar.log'
def debug(message):
if mylar.LOG_LEVEL > 1:
mylar_log.log(message, level='DEBUG')
def fdebug(message):
if mylar.LOG_LEVEL > 1:
mylar_log.log(message, level='DEBUG')
def info(message):
if mylar.LOG_LEVEL > 0:
mylar_log.log(message, level='INFO')
def warn(message):
mylar_log.log(message, level='WARNING')
def error(message):
mylar_log.log(message, level='ERROR')
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
if not PY2:
return str(obj, *args)
try:
return unicode(obj, *args)
except UnicodeDecodeError:
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text)
else:
# Mylar logger
logger = logging.getLogger('mylar')
class LogListHandler(logging.Handler):
"""
Log handler for Web UI.
"""
def emit(self, record):
message = self.format(record)
message = message.replace("\n", "<br />")
mylar.LOGLIST.insert(0, (helpers.now(), message, record.levelname, record.threadName))
def initLogger(console=False, log_dir=False, init=False, loglevel=1, max_logsize=None, max_logfiles=5):
#concurrentLogHandler/0.8.7 (to deal with windows locks)
#since this only happens on windows boxes, if it's nix/mac use the default logger.
if platform.system() == 'Windows':
#set the path to the lib here - just to make sure it can detect cloghandler & portalocker.
import sys
sys.path.append(os.path.join(mylar.PROG_DIR, 'lib'))
try:
from ConcurrentLogHandler.cloghandler import ConcurrentRotatingFileHandler as RFHandler
mylar.LOGTYPE = 'clog'
except ImportError:
mylar.LOGTYPE = 'log'
from logging.handlers import RotatingFileHandler as RFHandler
else:
mylar.LOGTYPE = 'log'
from logging.handlers import RotatingFileHandler as RFHandler
if all([init is True, max_logsize is None]):
max_logsize = 1000000 #1 MB
else:
if max_logsize is None:
max_logsize = 1000000 # 1 MB
"""
Setup logging for Mylar. It uses the logger instance with the name
'mylar'. Three log handlers are added:
* RotatingFileHandler: for the file Mylar.log
* LogListHandler: for Web UI
* StreamHandler: for console
"""
logging.getLogger('apscheduler.scheduler').setLevel(logging.WARN)
logging.getLogger('apscheduler.threadpool').setLevel(logging.WARN)
logging.getLogger('apscheduler.scheduler').propagate = False
logging.getLogger('apscheduler.threadpool').propagate = False
logging.getLogger('cherrypy').propagate = False
# Close and remove old handlers. This is required to reinit the loggers
# at runtime
for handler in logger.handlers[:]:
# Just make sure it is cleaned up.
if isinstance(handler, RFHandler):
handler.close()
elif isinstance(handler, logging.StreamHandler):
handler.flush()
logger.removeHandler(handler)
# Configure the logger to accept all messages
logger.propagate = False
if init is True:
logger.setLevel(logging.INFO)
else:
if loglevel == 1: #normal
logger.setLevel(logging.INFO)
elif loglevel >= 2: #verbose
logger.setLevel(logging.DEBUG)
# Add list logger
loglist_handler = LogListHandler()
loglist_handler.setLevel(logging.DEBUG)
logger.addHandler(loglist_handler)
# Setup file logger
if log_dir:
filename = os.path.join(log_dir, 'mylar.log')
file_formatter = Formatter('%(asctime)s - %(levelname)-7s :: %(name)s.%(funcName)s.%(lineno)s : %(threadName)s : %(message)s', '%d-%b-%Y %H:%M:%S')
file_handler = RFHandler(filename, "a", maxBytes=max_logsize, backupCount=max_logfiles)
if loglevel == 1: #normal
file_handler.setLevel(logging.INFO)
elif loglevel >= 2: #verbose
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(file_formatter)
logger.addHandler(file_handler)
# Setup console logger
if console:
console_formatter = logging.Formatter('%(asctime)s - %(levelname)s :: %(name)s.%(funcName)s.%(lineno)s : %(threadName)s : %(message)s', '%d-%b-%Y %H:%M:%S')
console_handler = logging.StreamHandler()
console_handler.setFormatter(console_formatter)
if loglevel == 1: #normal
console_handler.setLevel(logging.INFO)
elif loglevel >= 2: #verbose
console_handler.setLevel(logging.DEBUG)
logger.addHandler(console_handler)
# Install exception hooks
initHooks()
def initHooks(global_exceptions=True, thread_exceptions=True, pass_original=True):
"""
This method installs exception catching mechanisms. Any exception caught
will pass through the exception hook, and will be logged to the logger as
an error. Additionally, a traceback is provided.
This is very useful for crashing threads and any other bugs, that may not
be exposed when running as daemon.
The default exception hook is still considered, if pass_original is True.
"""
def excepthook(*exception_info):
# We should always catch this to prevent loops!
try:
message = "".join(traceback.format_exception(*exception_info))
logger.error("Uncaught exception: %s", message)
except:
pass
# Original excepthook
if pass_original:
sys.__excepthook__(*exception_info)
# Global exception hook
if global_exceptions:
sys.excepthook = excepthook
# Thread exception hook
if thread_exceptions:
old_init = threading.Thread.__init__
def new_init(self, *args, **kwargs):
old_init(self, *args, **kwargs)
old_run = self.run
def new_run(*args, **kwargs):
try:
old_run(*args, **kwargs)
except (KeyboardInterrupt, SystemExit):
raise
except:
excepthook(*sys.exc_info())
self.run = new_run
# Monkey patch the run() by monkey patching the __init__ method
threading.Thread.__init__ = new_init
# Expose logger methods
info = logger.info
warn = logger.warn
error = logger.error
debug = logger.debug
warning = logger.warning
message = logger.info
exception = logger.exception
fdebug = logger.debug
| 13,503 | Python | .py | 295 | 34.223729 | 168 | 0.602677 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,257 | updater.py | evilhero_mylar/mylar/updater.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import time
import datetime
from xml.dom.minidom import parseString
import urllib2
import shlex
import operator
import re
import os
import itertools
import sys
import exceptions
import mylar
from mylar import db, logger, helpers, filechecker
def dbUpdate(ComicIDList=None, calledfrom=None, sched=False):
if mylar.IMPORTLOCK:
logger.info('Import is currently running - deferring this until the next scheduled run sequence.')
return
myDB = db.DBConnection()
if ComicIDList is None:
if mylar.CONFIG.UPDATE_ENDED:
logger.info('Updating only Continuing Series (option enabled) - this might cause problems with the pull-list matching for rebooted series')
comiclist = []
completelist = myDB.select('SELECT LatestDate, ComicPublished, ForceContinuing, NewPublish, LastUpdated, ComicID, ComicName, Corrected_SeriesYear, Corrected_Type, ComicYear from comics WHERE Status="Active" or Status="Loading" order by LastUpdated DESC, LatestDate ASC')
for comlist in completelist:
if comlist['LatestDate'] is None:
recentstatus = 'Loading'
elif comlist['ComicPublished'] is None or comlist['ComicPublished'] == '' or comlist['LatestDate'] is None:
recentstatus = 'Unknown'
elif comlist['ForceContinuing'] == 1:
recentstatus = 'Continuing'
elif 'present' in comlist['ComicPublished'].lower() or (helpers.today()[:4] in comlist['LatestDate']):
latestdate = comlist['LatestDate']
c_date = datetime.date(int(latestdate[:4]), int(latestdate[5:7]), 1)
n_date = datetime.date.today()
recentchk = (n_date - c_date).days
if comlist['NewPublish']:
recentstatus = 'Continuing'
else:
if recentchk < 55:
recentstatus = 'Continuing'
else:
recentstatus = 'Ended'
else:
recentstatus = 'Ended'
if recentstatus == 'Continuing':
comiclist.append({"LatestDate": comlist['LatestDate'],
"LastUpdated": comlist['LastUpdated'],
"ComicID": comlist['ComicID'],
"ComicName": comlist['ComicName'],
"ComicYear": comlist['ComicYear'],
"Corrected_SeriesYear": comlist['Corrected_SeriesYear'],
"Corrected_Type": comlist['Corrected_Type']})
else:
comiclist = myDB.select('SELECT LatestDate, LastUpdated, ComicID, ComicName, ComicYear, Corrected_SeriesYear, Corrected_Type from comics WHERE Status="Active" or Status="Loading" order by LastUpdated DESC, latestDate ASC')
else:
comiclist = []
comiclisting = ComicIDList
for cl in comiclisting:
comiclist += myDB.select('SELECT ComicID, ComicName, ComicYear, Corrected_SeriesYear, Corrected_Type, LastUpdated from comics WHERE ComicID=? order by LastUpdated DESC, LatestDate ASC', [cl])
if all([sched is False, calledfrom is None]):
logger.info('Starting update for %i active comics' % len(comiclist))
cnt = 1
if sched is True:
logger.fdebug('Refresh sequence set to fire every %s minutes for %s day(s)' % (mylar.DBUPDATE_INTERVAL, mylar.CONFIG.REFRESH_CACHE))
for comic in sorted(comiclist, key=operator.itemgetter('LastUpdated'), reverse=True):
dspyear = comic['ComicYear']
csyear = None
fixed_type = None
if comic['Corrected_Type'] is not None:
fixed_type = comic['Corrected_Type']
if comic['Corrected_SeriesYear'] is not None:
csyear = comic['Corrected_SeriesYear']
if int(csyear) != int(comic['ComicYear']):
comic['ComicYear'] = csyear
dspyear = csyear
if ComicIDList is None:
ComicID = comic['ComicID']
ComicName = comic['ComicName']
c_date = comic['LastUpdated']
if c_date is None:
logger.error(ComicName + ' failed during a previous add /refresh as it has no Last Update timestamp. Forcing refresh now.')
else:
c_obj_date = datetime.datetime.strptime(c_date, "%Y-%m-%d %H:%M:%S")
n_date = datetime.datetime.now()
absdiff = abs(n_date - c_obj_date)
hours = (absdiff.days * 24 * 60 * 60 + absdiff.seconds) / 3600.0
cache_hours = mylar.CONFIG.REFRESH_CACHE * 24
if hours < cache_hours:
#logger.fdebug('%s [%s] Was refreshed less than %s hours ago. Skipping Refresh at this time.' % (ComicName, ComicID, cache_hours))
cnt +=1
continue
logger.info('[%s/%s] Refreshing :%s (%s) [%s]' % (cnt, len(comiclist), ComicName, dspyear, ComicID))
else:
ComicID = comic['ComicID']
ComicName = comic['ComicName']
logger.info('Refreshing/Updating: %s (%s) [%s]' % (ComicName, dspyear, ComicID))
mismatch = "no"
if not mylar.CONFIG.CV_ONLY or ComicID[:1] == "G":
CV_EXcomicid = myDB.selectone("SELECT * from exceptions WHERE ComicID=?", [ComicID]).fetchone()
if CV_EXcomicid is None: pass
else:
if CV_EXcomicid['variloop'] == '99':
mismatch = "yes"
if ComicID[:1] == "G":
mylar.importer.GCDimport(ComicID)
else:
cchk = importer.addComictoDB(ComicID, mismatch)
else:
if mylar.CONFIG.CV_ONETIMER == 1:
if sched is True:
helpers.job_management(write=True, job='DB Updater', current_run=helpers.utctimestamp(), status='Running')
mylar.UPDATER_STATUS = 'Running'
logger.fdebug("CV_OneTimer option enabled...")
#in order to update to JUST CV_ONLY, we need to delete the issues for a given series so it's a clea$
logger.fdebug("Gathering the status of all issues for the series.")
issues = myDB.select('SELECT * FROM issues WHERE ComicID=?', [ComicID])
if not issues:
#if issues are None it's probably a bad refresh/maxed out API that resulted in the issue data
#getting wiped out and not refreshed. Setting whack=True will force a complete refresh.
logger.fdebug('No issue data available. This is Whack.')
whack = True
else:
#check for series that are numerically out of whack (ie. 5/4)
logger.fdebug('Checking how out of whack the series is.')
whack = helpers.havetotals(refreshit=ComicID)
if calledfrom == 'weekly':
if whack == True:
logger.info('Series is out of whack. Forcibly refreshing series to ensure everything is in order.')
return True
else:
return False
annload = [] #initiate the list here so we don't error out below.
if mylar.CONFIG.ANNUALS_ON:
#now we load the annuals into memory to pass through to importer when refreshing so that it can
#refresh even the manually added annuals.
annual_load = myDB.select('SELECT * FROM annuals WHERE ComicID=?', [ComicID])
logger.fdebug('checking annual db')
for annthis in annual_load:
if not any(d['ReleaseComicID'] == annthis['ReleaseComicID'] for d in annload):
#print 'matched on annual'
annload.append({
'ReleaseComicID': annthis['ReleaseComicID'],
'ReleaseComicName': annthis['ReleaseComicName'],
'ComicID': annthis['ComicID'],
'ComicName': annthis['ComicName']
})
#print 'added annual'
issues += annual_load #myDB.select('SELECT * FROM annuals WHERE ComicID=?', [ComicID])
#store the issues' status for a given comicid, after deleting and readding, flip the status back to$
#logger.fdebug("Deleting all issue data.")
#myDB.action('DELETE FROM issues WHERE ComicID=?', [ComicID])
#myDB.action('DELETE FROM annuals WHERE ComicID=?', [ComicID])
logger.fdebug("Refreshing the series and pulling in new data using only CV.")
if whack == False:
chkstatus = mylar.importer.addComictoDB(ComicID, mismatch, calledfrom='dbupdate', annload=annload, csyear=csyear, fixed_type=fixed_type)
if chkstatus['status'] == 'complete':
#delete the data here if it's all valid.
logger.fdebug("Deleting all old issue data to make sure new data is clean...")
myDB.action('DELETE FROM issues WHERE ComicID=?', [ComicID])
myDB.action('DELETE FROM annuals WHERE ComicID=?', [ComicID])
mylar.importer.issue_collection(chkstatus['issuedata'], nostatus='True')
#need to update annuals at this point too....
if chkstatus['anndata'] is not None:
mylar.importer.manualAnnual(annchk=chkstatus['anndata'])
else:
logger.warn('There was an error when refreshing this series - Make sure directories are writable/exist, etc')
return
issues_new = myDB.select('SELECT * FROM issues WHERE ComicID=?', [ComicID])
annuals = []
ann_list = []
#reload the annuals here.
if mylar.CONFIG.ANNUALS_ON:
annuals_list = myDB.select('SELECT * FROM annuals WHERE ComicID=?', [ComicID])
ann_list += annuals_list
issues_new += annuals_list
logger.fdebug("Attempting to put the Status' back how they were.")
icount = 0
#the problem - the loop below will not match on NEW issues that have been refreshed that weren't present in the
#db before (ie. you left Mylar off for abit, and when you started it up it pulled down new issue information)
#need to test if issuenew['Status'] is None, but in a seperate loop below.
fndissue = []
for issue in issues:
for issuenew in issues_new:
#logger.fdebug(str(issue['Issue_Number']) + ' - issuenew:' + str(issuenew['IssueID']) + ' : ' + str(issuenew['Status']))
#logger.fdebug(str(issue['Issue_Number']) + ' - issue:' + str(issue['IssueID']) + ' : ' + str(issue['Status']))
try:
if issuenew['IssueID'] == issue['IssueID']:
newVAL = None
ctrlVAL = {"IssueID": issue['IssueID']}
if any([issuenew['Status'] != issue['Status'], issue['IssueDate_Edit'] is not None]):
#if the status is None and the original status is either Downloaded / Archived, keep status & stats
if issuenew['Status'] == None and (issue['Status'] == 'Downloaded' or issue['Status'] == 'Archived'):
newVAL = {"Location": issue['Location'],
"ComicSize": issue['ComicSize'],
"Status": issue['Status']}
#if the status is now Downloaded/Snatched, keep status & stats (downloaded only)
elif issuenew['Status'] == 'Downloaded' or issue['Status'] == 'Snatched':
newVAL = {"Location": issue['Location'],
"ComicSize": issue['ComicSize']}
if issuenew['Status'] == 'Downloaded':
newVAL['Status'] = issuenew['Status']
else:
newVAL['Status'] = issue['Status']
elif issue['Status'] == 'Archived':
newVAL = {"Status": issue['Status'],
"Location": issue['Location'],
"ComicSize": issue['ComicSize']}
else:
#change the status to the previous status
newVAL = {"Status": issue['Status']}
if all([issuenew['Status'] == None, issue['Status'] == 'Skipped']):
if issuenew['ReleaseDate'] == '0000-00-00':
dk = re.sub('-', '', issue['IssueDate']).strip()
else:
dk = re.sub('-', '', issuenew['ReleaseDate']).strip() # converts date to 20140718 format
if dk == '0000-00-00':
logger.warn('Issue Data is invalid for Issue Number %s. Marking this issue as Skipped' % issue['Issue_Number'])
newVAL = {"Status": "Skipped"}
else:
datechk = datetime.datetime.strptime(dk, "%Y%m%d")
nowdate = datetime.datetime.now()
now_week = datetime.datetime.strftime(nowdate, "%Y%U")
issue_week = datetime.datetime.strftime(datechk, "%Y%U")
if mylar.CONFIG.AUTOWANT_ALL:
newVAL = {"Status": "Wanted"}
elif issue_week >= now_week:
logger.fdebug('Issue_week: %s -- now_week: %s' % (issue_week, now_week))
logger.fdebug('Issue date [%s] is in/beyond current week - marking as Wanted.' % dk)
newVAL = {"Status": "Wanted"}
else:
newVAL = {"Status": "Skipped"}
if newVAL is not None:
if issue['IssueDate_Edit']:
logger.fdebug('[#' + str(issue['Issue_Number']) + '] detected manually edited Issue Date.')
logger.fdebug('new value : ' + str(issue['IssueDate']) + ' ... cv value : ' + str(issuenew['IssueDate']))
newVAL['IssueDate'] = issue['IssueDate']
newVAL['IssueDate_Edit'] = issue['IssueDate_Edit']
if any(d['IssueID'] == str(issue['IssueID']) for d in ann_list):
logger.fdebug("annual detected for " + str(issue['IssueID']) + " #: " + str(issue['Issue_Number']))
myDB.upsert("Annuals", newVAL, ctrlVAL)
else:
#logger.fdebug('#' + str(issue['Issue_Number']) + ' writing issuedata: ' + str(newVAL))
myDB.upsert("Issues", newVAL, ctrlVAL)
fndissue.append({"IssueID": issue['IssueID']})
icount+=1
break
except (RuntimeError, TypeError, ValueError, OSError) as e:
logger.warn('Something is out of whack somewhere with the series: %s' % e)
#if it's an annual (ie. deadpool-2011 ) on a refresh will throw index errors for some reason.
except:
logger.warn('Unexpected Error: %s' % sys.exc_info()[0])
raise
logger.info("In the process of converting the data to CV, I changed the status of " + str(icount) + " issues.")
issuesnew = myDB.select('SELECT * FROM issues WHERE ComicID=? AND Status is NULL', [ComicID])
if mylar.CONFIG.AUTOWANT_UPCOMING:
newstatus = "Wanted"
else:
newstatus = "Skipped"
newiss = []
for iss in issuesnew:
newiss.append({"IssueID": iss['IssueID'],
"Status": newstatus,
"Annual": False})
if mylar.CONFIG.ANNUALS_ON:
annualsnew = myDB.select('SELECT * FROM annuals WHERE ComicID=? AND Status is NULL', [ComicID])
for ann in annualsnew:
newiss.append({"IssueID": iss['IssueID'],
"Status": newstatus,
"Annual": True})
if len(newiss) > 0:
for newi in newiss:
ctrlVAL = {"IssueID": newi['IssueID']}
newVAL = {"Status": newi['Status']}
#logger.fdebug('writing issuedata: ' + str(newVAL))
if newi['Annual'] == True:
myDB.upsert("Annuals", newVAL, ctrlVAL)
else:
myDB.upsert("Issues", newVAL, ctrlVAL)
logger.info('I have added ' + str(len(newiss)) + ' new issues for this series that were not present before.')
forceRescan(ComicID)
else:
chkstatus = mylar.importer.addComictoDB(ComicID, mismatch, annload=annload, csyear=csyear)
#if cchk:
# #delete the data here if it's all valid.
# #logger.fdebug("Deleting all old issue data to make sure new data is clean...")
# myDB.action('DELETE FROM issues WHERE ComicID=?', [ComicID])
# myDB.action('DELETE FROM annuals WHERE ComicID=?', [ComicID])
# mylar.importer.issue_collection(cchk, nostatus='True')
# #need to update annuals at this point too....
# if annchk:
# mylar.importer.manualAnnual(annchk=annchk)
else:
chkstatus = mylar.importer.addComictoDB(ComicID, mismatch)
cnt += 1
if all([sched is False, calledfrom != 'refresh']):
time.sleep(15) #pause for 15 secs so dont hammer CV and get 500 error
else:
break
helpers.job_management(write=True, job='DB Updater', last_run_completed=helpers.utctimestamp(), status='Waiting')
mylar.UPDATER_STATUS = 'Waiting'
logger.info('Update complete')
def latest_update(ComicID, LatestIssue, LatestDate):
# here we add to comics.latest
logger.fdebug(str(ComicID) + ' - updating latest_date to : ' + str(LatestDate))
myDB = db.DBConnection()
latestCTRLValueDict = {"ComicID": ComicID}
newlatestDict = {"LatestIssue": str(LatestIssue),
"LatestDate": str(LatestDate)}
myDB.upsert("comics", newlatestDict, latestCTRLValueDict)
def upcoming_update(ComicID, ComicName, IssueNumber, IssueDate, forcecheck=None, futurepull=None, altissuenumber=None, weekinfo=None):
# here we add to upcoming table...
myDB = db.DBConnection()
dspComicName = ComicName #to make sure that the word 'annual' will be displayed on screen
if 'annual' in ComicName.lower():
adjComicName = re.sub("\\bannual\\b", "", ComicName.lower()) # for use with comparisons.
logger.fdebug('annual detected - adjusting name to : ' + adjComicName)
else:
adjComicName = ComicName
controlValue = {"ComicID": ComicID}
newValue = {"ComicName": adjComicName,
"IssueNumber": str(IssueNumber),
"DisplayComicName": dspComicName,
"IssueDate": str(IssueDate)}
#let's refresh the series here just to make sure if an issue is available/not.
mismatch = "no"
CV_EXcomicid = myDB.selectone("SELECT * from exceptions WHERE ComicID=?", [ComicID]).fetchone()
if CV_EXcomicid is None:
pass
else:
if CV_EXcomicid['variloop'] == '99':
mismatch = "yes"
if mylar.CONFIG.ALT_PULL != 2 or mylar.PULLBYFILE is True:
lastupdatechk = myDB.selectone("SELECT * FROM comics WHERE ComicID=?", [ComicID]).fetchone()
if lastupdatechk is None:
pullupd = "yes"
else:
c_date = lastupdatechk['LastUpdated']
if c_date is None:
logger.error(lastupdatechk['ComicName'] + ' failed during a previous add /refresh. Please either delete and readd the series, or try a refresh of the series.')
return
c_obj_date = datetime.datetime.strptime(c_date, "%Y-%m-%d %H:%M:%S")
n_date = datetime.datetime.now()
absdiff = abs(n_date - c_obj_date)
hours = (absdiff.days * 24 * 60 * 60 + absdiff.seconds) / 3600.0
else:
#if it's at this point and the refresh is None, odds are very good that it's already up-to-date so let it flow thru
if mylar.CONFIG.PULL_REFRESH is None:
mylar.CONFIG.PULL_REFRESH = datetime.datetime.today().replace(second=0,microsecond=0)
#update the PULL_REFRESH
#mylar.config_write()
logger.fdebug('pull_refresh: ' + str(mylar.CONFIG.PULL_REFRESH))
c_obj_date = datetime.datetime.strptime(str(mylar.CONFIG.PULL_REFRESH),"%Y-%m-%d %H:%M:%S")
#logger.fdebug('c_obj_date: ' + str(c_obj_date))
n_date = datetime.datetime.now()
#logger.fdebug('n_date: ' + str(n_date))
absdiff = abs(n_date - c_obj_date)
#logger.fdebug('absdiff: ' + str(absdiff))
hours = (absdiff.days * 24 * 60 * 60 + absdiff.seconds) / 3600.0
#logger.fdebug('hours: ' + str(hours))
if any(['annual' in ComicName.lower(), 'special' in ComicName.lower()]):
if mylar.CONFIG.ANNUALS_ON:
logger.info('checking: ' + str(ComicID) + ' -- issue#: ' + str(IssueNumber))
issuechk = myDB.selectone("SELECT * FROM annuals WHERE ComicID=? AND Issue_Number=?", [ComicID, IssueNumber]).fetchone()
else:
logger.fdebug('Non-standard issue detected (annual/special/etc), but Annual Integration is not enabled. Ignoring result.')
return
else:
issuechk = myDB.selectone("SELECT * FROM issues WHERE ComicID=? AND Issue_Number=?", [ComicID, IssueNumber]).fetchone()
if issuechk is None and altissuenumber is not None:
logger.info('altissuenumber is : ' + str(altissuenumber))
issuechk = myDB.selectone("SELECT * FROM issues WHERE ComicID=? AND Int_IssueNumber=?", [ComicID, helpers.issuedigits(altissuenumber)]).fetchone()
if issuechk is None:
if futurepull is None:
og_status = None
if mylar.CONFIG.ALT_PULL != 2 or mylar.PULLBYFILE is True:
logger.fdebug(adjComicName + ' Issue: ' + str(IssueNumber) + ' not present in listings to mark for download...updating comic and adding to Upcoming Wanted Releases.')
# we need to either decrease the total issue count, OR indicate that an issue is upcoming.
upco_results = myDB.select("SELECT COUNT(*) FROM UPCOMING WHERE ComicID=?", [ComicID])
upco_iss = upco_results[0][0]
#logger.info("upco_iss: " + str(upco_iss))
if int(upco_iss) > 0:
#logger.info("There is " + str(upco_iss) + " of " + str(ComicName) + " that's not accounted for")
newKey = {"ComicID": ComicID}
newVal = {"not_updated_db": str(upco_iss)}
myDB.upsert("comics", newVal, newKey)
elif int(upco_iss) <=0 and lastupdatechk['not_updated_db']:
#if not_updated_db has a value, and upco_iss is > 0, let's zero it back out cause it's updated now.
newKey = {"ComicID": ComicID}
newVal = {"not_updated_db": ""}
myDB.upsert("comics", newVal, newKey)
if hours > 5 or forcecheck == 'yes':
pullupd = "yes"
logger.fdebug('Now Refreshing comic ' + ComicName + ' to make sure it is up-to-date')
if ComicID[:1] == "G":
mylar.importer.GCDimport(ComicID, pullupd)
else:
cchk = mylar.importer.updateissuedata(ComicID, ComicName, calledfrom='weeklycheck') #mylar.importer.addComictoDB(ComicID,mismatch,pullupd)
else:
logger.fdebug('It has not been longer than 5 hours since we last did this...we will wait so we do not hammer things.')
else:
logger.fdebug('[WEEKLY-PULL] Walksoftly has been enabled. ComicID/IssueID control given to the ninja to monitor.')
logger.fdebug('hours: ' + str(hours) + ' -- forcecheck: ' + str(forcecheck))
if hours > 2 or forcecheck == 'yes':
logger.fdebug('weekinfo:' + str(weekinfo))
mylar.CONFIG.PULL_REFRESH = datetime.datetime.today().replace(second=0,microsecond=0)
#update the PULL_REFRESH
#mylar.config_write()
chkitout = mylar.locg.locg(weeknumber=str(weekinfo['weeknumber']),year=str(weekinfo['year']))
logger.fdebug('linking ComicID to Pull-list to reflect status.')
downstats = {"ComicID": ComicID,
"IssueID": None,
"Status": None}
return downstats
else:
# if futurepull is not None, let's just update the status and ComicID
# NOTE: THIS IS CREATING EMPTY ENTRIES IN THE FUTURE TABLE. ???
nKey = {"ComicID": ComicID}
nVal = {"Status": "Wanted"}
myDB.upsert("future", nVal, nKey)
return
if issuechk is not None:
if issuechk['Issue_Number'] == IssueNumber or issuechk['Issue_Number'] == altissuenumber:
og_status = issuechk['Status']
#check for 'out-of-whack' series here.
whackness = dbUpdate([ComicID], calledfrom='weekly', sched=False)
if any([whackness == True, og_status is None]):
if any([issuechk['Status'] == 'Downloaded', issuechk['Status'] == 'Archived', issuechk['Status'] == 'Snatched']):
logger.fdebug('Forcibly maintaining status of : ' + og_status + ' for #' + issuechk['Issue_Number'] + ' to ensure integrity.')
logger.fdebug('Comic series has an incorrect total count. Forcily refreshing series to ensure data is current.')
dbUpdate([ComicID])
issuechk = myDB.selectone("SELECT * FROM issues WHERE ComicID=? AND Int_IssueNumber=?", [ComicID, helpers.issuedigits(IssueNumber)]).fetchone()
if issuechk['Status'] != og_status and (issuechk['Status'] != 'Downloaded' or issuechk['Status'] != 'Archived' or issuechk['Status'] != 'Snatched'):
logger.fdebug('Forcibly changing status of %s back to %s for #%s to stop repeated downloads.' % (issuechk['Status'], og_status, issuechk['Issue_Number']))
else:
logger.fdebug('[%s] / [%s] Status has not changed during refresh or is marked as being Wanted/Skipped correctly.' % (issuechk['Status'], og_status))
og_status = issuechk['Status']
else:
logger.fdebug('Comic series already up-to-date ... no need to refresh at this time.')
logger.fdebug('Available to be marked for download - checking...' + adjComicName + ' Issue: ' + str(issuechk['Issue_Number']))
logger.fdebug('...Existing status: ' + og_status)
control = {"IssueID": issuechk['IssueID']}
newValue['IssueID'] = issuechk['IssueID']
if og_status == "Snatched":
values = {"Status": "Snatched"}
newValue['Status'] = "Snatched"
elif og_status == "Downloaded":
values = {"Status": "Downloaded"}
newValue['Status'] = "Downloaded"
#if the status is Downloaded and it's on the pullist - let's mark it so everyone can bask in the glory
elif og_status == "Wanted":
values = {"Status": "Wanted"}
newValue['Status'] = "Wanted"
elif og_status == "Archived":
values = {"Status": "Archived"}
newValue['Status'] = "Archived"
elif og_status == 'Failed':
if mylar.CONFIG.FAILED_DOWNLOAD_HANDLING:
if mylar.CONFIG.FAILED_AUTO:
values = {"Status": "Wanted"}
newValue['Status'] = "Wanted"
else:
values = {"Status": "Failed"}
newValue['Status'] = "Failed"
else:
values = {"Status": "Skipped"}
newValue['Status'] = "Skipped"
else:
values = {"Status": "Skipped"}
newValue['Status'] = "Skipped"
#was in wrong place :(
else:
logger.fdebug('Issues do not match for some reason...weekly new issue: %s' % IssueNumber)
return
if mylar.CONFIG.AUTOWANT_UPCOMING:
#for issues not in db - to be added to Upcoming table.
if og_status is None:
newValue['Status'] = "Wanted"
logger.fdebug('...Changing Status to Wanted and throwing it in the Upcoming section since it is not published yet.')
#this works for issues existing in DB...
elif og_status == "Skipped":
newValue['Status'] = "Wanted"
values = {"Status": "Wanted"}
logger.fdebug('...New status of Wanted')
elif og_status == "Wanted":
logger.fdebug('...Status already Wanted .. not changing.')
else:
logger.fdebug('...Already have issue - keeping existing status of : ' + og_status)
if issuechk is None:
myDB.upsert("upcoming", newValue, controlValue)
logger.fdebug('updating Pull-list to reflect status.')
downstats = {"Status": newValue['Status'],
"ComicID": ComicID,
"IssueID": None}
return downstats
else:
logger.fdebug('--attempt to find errant adds to Wanted list')
logger.fdebug('UpcomingNewValue: ' + str(newValue))
logger.fdebug('UpcomingcontrolValue: ' + str(controlValue))
if issuechk['IssueDate'] == '0000-00-00' and newValue['IssueDate'] != '0000-00-00':
logger.fdebug('Found a 0000-00-00 issue - force updating series to try and get it proper.')
dateVal = {"IssueDate": newValue['IssueDate'],
"ComicName": issuechk['ComicName'],
"Status": newValue['Status'],
"IssueNumber": issuechk['Issue_Number']}
logger.fdebug('updating date in upcoming table to : ' + str(newValue['IssueDate']) + '[' + newValue['Status'] + ']')
logger.fdebug('ComicID:' + str(controlValue))
myDB.upsert("upcoming", dateVal, controlValue)
logger.fdebug('Temporarily putting the Issue Date for ' + str(issuechk['Issue_Number']) + ' to ' + str(newValue['IssueDate']))
values = {"IssueDate": newValue['IssueDate']}
#if ComicID[:1] == "G": mylar.importer.GCDimport(ComicID,pullupd='yes')
#else: mylar.importer.addComictoDB(ComicID,mismatch,pullupd='yes')
if any(['annual' in ComicName.lower(), 'special' in ComicName.lower()]):
myDB.upsert("annuals", values, control)
else:
myDB.upsert("issues", values, control)
if any([og_status == 'Downloaded', og_status == 'Archived', og_status == 'Snatched', og_status == 'Wanted', newValue['Status'] == 'Wanted']):
logger.fdebug('updating Pull-list to reflect status change: ' + og_status + '[' + newValue['Status'] + ']')
if og_status != 'Skipped':
downstats = {"Status": og_status,
"ComicID": issuechk['ComicID'],
"IssueID": issuechk['IssueID']}
else:
downstats = {"Status": newValue['Status'],
"ComicID": issuechk['ComicID'],
"IssueID": issuechk['IssueID']}
return downstats
def weekly_update(ComicName, IssueNumber, CStatus, CID, weeknumber, year, altissuenumber=None):
logger.fdebug('Weekly Update for week ' + str(weeknumber) + '-' + str(year) + ' : ' + str(ComicName) + ' #' + str(IssueNumber) + ' to a status of ' + str(CStatus))
if altissuenumber:
logger.fdebug('weekly_update of table : ' + str(ComicName) + ' (Alternate Issue #):' + str(altissuenumber) + ' to a status of ' + str(CStatus))
# here we update status of weekly table...
# added Issue to stop false hits on series' that have multiple releases in a week
# added CStatus to update status flags on Pullist screen
myDB = db.DBConnection()
issuecheck = myDB.selectone("SELECT * FROM weekly WHERE COMIC=? AND ISSUE=? and WEEKNUMBER=? AND YEAR=?", [ComicName, IssueNumber, int(weeknumber), year]).fetchone()
if issuecheck is not None:
controlValue = {"COMIC": str(ComicName),
"ISSUE": str(IssueNumber),
"WEEKNUMBER": int(weeknumber),
"YEAR": year}
logger.info('controlValue:' + str(controlValue))
try:
if CID['IssueID']:
cidissueid = CID['IssueID']
else:
cidissueid = None
except:
cidissueid = None
logger.info('CStatus:' + str(CStatus))
if CStatus:
newValue = {"STATUS": CStatus}
else:
if mylar.CONFIG.AUTOWANT_UPCOMING:
newValue = {"STATUS": "Wanted"}
else:
newValue = {"STATUS": "Skipped"}
#setting this here regardless, as it will be a match for a watchlist hit at this point anyways - so link it here what's availalbe.
newValue['ComicID'] = CID['ComicID']
newValue['IssueID'] = cidissueid
logger.info('newValue:' + str(newValue))
myDB.upsert("weekly", newValue, controlValue)
def newpullcheck(ComicName, ComicID, issue=None):
# When adding a new comic, let's check for new issues on this week's pullist and update.
if mylar.CONFIG.ALT_PULL != 2 or mylar.PULLBYFILE is True:
mylar.weeklypull.pullitcheck(comic1off_name=ComicName, comic1off_id=ComicID, issue=issue)
else:
mylar.weeklypull.new_pullcheck(weeknumber=mylar.CURRENT_WEEKNUMBER, pullyear=mylar.CURRENT_YEAR, comic1off_name=ComicName, comic1off_id=ComicID, issue=issue)
return
def no_searchresults(ComicID):
# when there's a mismatch between CV & GCD - let's change the status to
# something other than 'Loaded'
myDB = db.DBConnection()
controlValue = {"ComicID": ComicID}
newValue = {"Status": "Error",
"LatestDate": "Error",
"LatestIssue": "Error"}
myDB.upsert("comics", newValue, controlValue)
def nzblog(IssueID, NZBName, ComicName, SARC=None, IssueArcID=None, id=None, prov=None, alt_nzbname=None, oneoff=False):
myDB = db.DBConnection()
newValue = {'NZBName': NZBName}
if SARC:
logger.fdebug("Story Arc (SARC) detected as: " + str(SARC))
IssueID = 'S' + str(IssueArcID)
newValue['SARC'] = SARC
if oneoff is True:
logger.fdebug('One-Off download detected when updating - crossing the t\'s and dotting the i\'s so things work...')
newValue['OneOff'] = True
if IssueID is None or IssueID == 'None':
#if IssueID is None, it's a one-off download from the pull-list.
#give it a generic ID above the last one so it doesn't throw an error later.
if any([mylar.CONFIG.HIGHCOUNT == 0, mylar.CONFIG.HIGHCOUNT is None]):
mylar.CONFIG.HIGHCOUNT = 900000
else:
mylar.CONFIG.HIGHCOUNT+=1
IssueID = mylar.CONFIG.HIGHCOUNT
#mylar.config_write()
controlValue = {"IssueID": IssueID,
"Provider": prov}
if id:
logger.info('setting the nzbid for this download grabbed by ' + prov + ' in the nzblog to : ' + str(id))
newValue['ID'] = id
if alt_nzbname:
logger.info('setting the alternate nzbname for this download grabbed by ' + prov + ' in the nzblog to : ' + alt_nzbname)
newValue['AltNZBName'] = alt_nzbname
#check if it exists already in the log.
chkd = myDB.selectone('SELECT * FROM nzblog WHERE IssueID=? and Provider=?', [IssueID, prov]).fetchone()
if chkd is None:
pass
else:
altnames = chkd['AltNZBName']
if any([altnames is None, altnames == '']):
#we need to wipe the entry so we can re-update with the alt-nzbname if required
myDB.action('DELETE FROM nzblog WHERE IssueID=? and Provider=?', [IssueID, prov])
logger.fdebug('Deleted stale entry from nzblog for IssueID: ' + str(IssueID) + ' [' + prov + ']')
myDB.upsert("nzblog", newValue, controlValue)
def foundsearch(ComicID, IssueID, mode=None, down=None, provider=None, SARC=None, IssueArcID=None, module=None, hash=None, crc=None, comicname=None, issuenumber=None, pullinfo=None):
# When doing a Force Search (Wanted tab), the resulting search calls this to update.
# this is all redudant code that forceRescan already does.
# should be redone at some point so that instead of rescanning entire
# series directory, it just scans for the issue it just downloaded and
# and change the status to Snatched accordingly. It is not to increment the have count
# at this stage as it's not downloaded - just the .nzb has been snatched and sent to SAB.
if module is None:
module = ''
module += '[UPDATER]'
myDB = db.DBConnection()
modcomicname = False
logger.fdebug(module + ' comicid: ' + str(ComicID))
logger.fdebug(module + ' issueid: ' + str(IssueID))
if mode != 'pullwant':
if mode != 'story_arc':
comic = myDB.selectone('SELECT * FROM comics WHERE ComicID=?', [ComicID]).fetchone()
ComicName = comic['ComicName']
if mode == 'want_ann':
issue = myDB.selectone('SELECT * FROM annuals WHERE IssueID=?', [IssueID]).fetchone()
if ComicName != issue['ReleaseComicName'] + ' Annual':
ComicName = issue['ReleaseComicName']
modcomicname = True
else:
issue = myDB.selectone('SELECT * FROM issues WHERE IssueID=?', [IssueID]).fetchone()
CYear = issue['IssueDate'][:4]
IssueNum = issue['Issue_Number']
else:
issue = myDB.selectone('SELECT * FROM storyarcs WHERE IssueArcID=?', [IssueArcID]).fetchone()
ComicName = issue['ComicName']
CYear = issue['IssueYEAR']
IssueNum = issue['IssueNumber']
else:
oneinfo = myDB.selectone('SELECT * FROM weekly WHERE IssueID=?', [IssueID]).fetchone()
if oneinfo is None:
ComicName = comicname
IssueNum = issuenumber
onefail = True
else:
ComicName = oneinfo['COMIC']
IssueNum = oneinfo['ISSUE']
onefail = False
if down is None:
# update the status to Snatched (so it won't keep on re-downloading!)
logger.info(module + ' Updating status to snatched')
logger.fdebug(module + ' Provider is ' + provider)
if hash:
logger.fdebug(module + ' Hash set to : ' + hash)
newValue = {"Status": "Snatched"}
if mode == 'story_arc':
cValue = {"IssueArcID": IssueArcID}
snatchedupdate = {"IssueArcID": IssueArcID}
myDB.upsert("storyarcs", newValue, cValue)
# update the snatched DB
snatchedupdate = {"IssueID": IssueArcID,
"Status": "Snatched",
"Provider": provider
}
else:
if mode == 'want_ann':
controlValue = {"IssueID": IssueID}
myDB.upsert("annuals", newValue, controlValue)
else:
controlValue = {"IssueID": IssueID}
if mode != 'pullwant':
myDB.upsert("issues", newValue, controlValue)
# update the snatched DB
snatchedupdate = {"IssueID": IssueID,
"Status": "Snatched",
"Provider": provider
}
if mode == 'story_arc':
IssueNum = issue['IssueNumber']
newsnatchValues = {"ComicName": ComicName,
"ComicID": 'None',
"Issue_Number": IssueNum,
"DateAdded": helpers.now(),
"Status": "Snatched",
"Hash": hash
}
myDB.upsert("snatched", newsnatchValues, snatchedupdate)
elif mode != 'pullwant':
if modcomicname:
IssueNum = issue['Issue_Number']
else:
if mode == 'want_ann':
IssueNum = "Annual " + issue['Issue_Number']
else:
IssueNum = issue['Issue_Number']
newsnatchValues = {"ComicName": ComicName,
"ComicID": ComicID,
"Issue_Number": IssueNum,
"DateAdded": helpers.now(),
"Status": "Snatched",
"Hash": hash
}
myDB.upsert("snatched", newsnatchValues, snatchedupdate)
else:
#updating snatched table with one-off is abit difficult due to lack of complete information in some instances
#ie. alt_pull 2 not populated yet, alt_pull 0 method in general doesn't have enough info....
newsnatchValues = {"ComicName": ComicName,
"ComicID": ComicID,
"IssueID": IssueID,
"Issue_Number": IssueNum,
"DateAdded": helpers.now(),
"Status": "Snatched",
"Hash": hash
}
myDB.upsert("snatched", newsnatchValues, snatchedupdate)
#this will update the weeklypull list immediately after snatching to reflect the new status.
#-is ugly, should be linked directly to other table (IssueID should be populated in weekly pull at this point hopefully).
chkit = myDB.selectone("SELECT * FROM weekly WHERE ComicID=? AND IssueID=?", [ComicID, IssueID]).fetchone()
if chkit is not None:
comicname = chkit['COMIC']
issue = chkit['ISSUE']
ctlVal = {"ComicID": ComicID,
"IssueID": IssueID}
myDB.upsert("weekly", newValue, ctlVal)
newValue['IssueNumber'] = issue
newValue['ComicName'] = comicname
newValue['Status'] = "Snatched"
if pullinfo is not None:
newValue['weeknumber'] = pullinfo['weeknumber']
newValue['year'] = pullinfo['year']
else:
try:
newValue['weeknumber'] = chkit['weeknumber']
newValue['year'] = chkit['year']
except:
pass
myDB.upsert("oneoffhistory", newValue, ctlVal)
logger.info('%s Updated the status (Snatched) complete for %s Issue: %s' % (module, ComicName, IssueNum))
else:
if down == 'PP':
logger.info(module + ' Setting status to Post-Processed in history.')
downstatus = 'Post-Processed'
else:
logger.info(module + ' Setting status to Downloaded in history.')
downstatus = 'Downloaded'
if mode == 'want_ann':
if not modcomicname:
IssueNum = "Annual " + IssueNum
elif mode == 'story_arc':
IssueID = IssueArcID
snatchedupdate = {"IssueID": IssueID,
"Status": downstatus,
"Provider": provider
}
newsnatchValues = {"ComicName": ComicName,
"ComicID": ComicID,
"Issue_Number": IssueNum,
"DateAdded": helpers.now(),
"Status": downstatus,
"crc": crc
}
myDB.upsert("snatched", newsnatchValues, snatchedupdate)
if mode == 'story_arc':
cValue = {"IssueArcID": IssueArcID}
nValue = {"Status": "Downloaded"}
myDB.upsert("storyarcs", nValue, cValue)
elif mode != 'pullwant':
controlValue = {"IssueID": IssueID}
newValue = {"Status": "Downloaded"}
if mode == 'want_ann':
myDB.upsert("annuals", newValue, controlValue)
else:
myDB.upsert("issues", newValue, controlValue)
#this will update the weeklypull list immediately after post-processing to reflect the new status.
chkit = myDB.selectone("SELECT * FROM weekly WHERE ComicID=? AND IssueID=? AND Status='Snatched'", [ComicID, IssueID]).fetchone()
if chkit is not None:
comicname = chkit['COMIC']
issue = chkit['ISSUE']
ctlVal = {"ComicID": ComicID,
"IssueID": IssueID}
newVal = {"Status": "Downloaded"}
myDB.upsert("weekly", newVal, ctlVal)
newVal['IssueNumber'] = issue
newVal['ComicName'] = comicname
newVal['Status'] = "Downloaded"
if pullinfo is not None:
newVal['weeknumber'] = pullinfo['weeknumber']
newVal['year'] = pullinfo['year']
myDB.upsert("oneoffhistory", newVal, ctlVal)
logger.info('%s Updating Status (%s) now completed for %s issue: %s' % (module, downstatus, ComicName, IssueNum))
return
def forceRescan(ComicID, archive=None, module=None, recheck=False):
if module is None:
module = ''
module += '[FILE-RESCAN]'
myDB = db.DBConnection()
# file check to see if issue exists
rescan = myDB.selectone('SELECT * FROM comics WHERE ComicID=?', [ComicID]).fetchone()
if rescan['AlternateSearch'] is not None:
altnames = rescan['AlternateSearch'] + '##'
else:
altnames = ''
if (all([rescan['Type'] != 'Print', rescan['Type'] != 'Digital', rescan['Type'] != 'None', rescan['Type'] is not None]) and rescan['Corrected_Type'] != 'Print') or rescan['Corrected_Type'] == 'TPB':
if rescan['Type'] == 'One-Shot' and rescan['Corrected_Type'] is None:
booktype = 'One-Shot'
else:
booktype = 'TPB'
else:
booktype = None
annscan = myDB.select('SELECT * FROM annuals WHERE ComicID=?', [ComicID])
if annscan is None:
pass
else:
for ascan in annscan:
#logger.info('ReleaseComicName: ' + ascan['ReleaseComicName'])
if ascan['ReleaseComicName'] not in altnames:
altnames += ascan['ReleaseComicName'] + '!!' + ascan['ReleaseComicID'] + '##'
altnames = altnames[:-2]
logger.info(module + ' Now checking files for ' + rescan['ComicName'] + ' (' + str(rescan['ComicYear']) + ') in ' + rescan['ComicLocation'])
fca = []
if archive is None:
tval = filechecker.FileChecker(dir=rescan['ComicLocation'], watchcomic=rescan['ComicName'], Publisher=rescan['ComicPublisher'], AlternateSearch=altnames)
tmpval = tval.listFiles()
#tmpval = filechecker.listFiles(dir=rescan['ComicLocation'], watchcomic=rescan['ComicName'], Publisher=rescan['ComicPublisher'], AlternateSearch=altnames)
comiccnt = int(tmpval['comiccount'])
#logger.fdebug(module + 'comiccnt is:' + str(comiccnt))
fca.append(tmpval)
try:
if all([mylar.CONFIG.MULTIPLE_DEST_DIRS is not None, mylar.CONFIG.MULTIPLE_DEST_DIRS != 'None', os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(rescan['ComicLocation'])) != rescan['ComicLocation'], os.path.exists(os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(rescan['ComicLocation'])))]):
logger.fdebug(module + 'multiple_dest_dirs:' + mylar.CONFIG.MULTIPLE_DEST_DIRS)
logger.fdebug(module + 'dir: ' + rescan['ComicLocation'])
logger.fdebug(module + 'os.path.basename: ' + os.path.basename(rescan['ComicLocation']))
pathdir = os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(rescan['ComicLocation']))
logger.info(module + ' Now checking files for ' + rescan['ComicName'] + ' (' + str(rescan['ComicYear']) + ') in :' + pathdir)
mvals = filechecker.FileChecker(dir=pathdir, watchcomic=rescan['ComicName'], Publisher=rescan['ComicPublisher'], AlternateSearch=altnames)
tmpv = mvals.listFiles()
#tmpv = filechecker.listFiles(dir=pathdir, watchcomic=rescan['ComicName'], Publisher=rescan['ComicPublisher'], AlternateSearch=altnames)
logger.fdebug(module + 'tmpv filecount: ' + str(tmpv['comiccount']))
comiccnt += int(tmpv['comiccount'])
fca.append(tmpv)
except:
pass
else:
# files_arc = filechecker.listFiles(dir=archive, watchcomic=rescan['ComicName'], Publisher=rescan['ComicPublisher'], AlternateSearch=rescan['AlternateSearch'])
arcval = filechecker.FileChecker(dir=archive, watchcomic=rescan['ComicName'], Publisher=rescan['ComicPublisher'], AlternateSearch=rescan['AlternateSearch'])
files_arc = arcval.listFiles()
fca.append(files_arc)
comiccnt = int(files_arc['comiccount'])
fcb = []
fc = {}
is_cnt = myDB.select("SELECT COUNT(*) FROM issues WHERE ComicID=?", [ComicID])
iscnt = is_cnt[0][0]
for ca in fca:
i = 0
while True:
try:
cla = ca['comiclist'][i]
except (IndexError, KeyError) as e:
break
try:
if all([booktype == 'TPB', iscnt > 1]) or all([booktype == 'One-Shot', iscnt == 1, cla['JusttheDigits'] is None]):
if cla['SeriesVolume'] is not None:
just_the_digits = re.sub('[^0-9]', '', cla['SeriesVolume']).strip()
else:
just_the_digits = re.sub('[^0-9]', '', cla['JusttheDigits']).strip()
else:
just_the_digits = cla['JusttheDigits']
except Exception as e:
logger.warn('[Exception: %s] Unable to properly match up/retrieve issue number (or volume) for this [CS: %s]' % (e,cla))
else:
fcb.append({"ComicFilename": cla['ComicFilename'],
"ComicLocation": cla['ComicLocation'],
"ComicSize": cla['ComicSize'],
"JusttheDigits": just_the_digits,
"AnnualComicID": cla['AnnualComicID']})
i+=1
fc['comiclist'] = fcb
havefiles = 0
if mylar.CONFIG.ANNUALS_ON:
an_cnt = myDB.select("SELECT COUNT(*) FROM annuals WHERE ComicID=?", [ComicID])
anncnt = an_cnt[0][0]
else:
anncnt = 0
fccnt = comiccnt #int(fc['comiccount'])
issnum = 1
fcnew = []
fn = 0
issuedupechk = []
annualdupechk = []
issueexceptdupechk = []
mc_issue = []
mc_issuenumber = []
multiple_check = myDB.select('SELECT * FROM issues WHERE ComicID=? GROUP BY Int_IssueNumber HAVING (COUNT(Int_IssueNumber) > 1)', [ComicID])
if len(multiple_check) == 0:
logger.fdebug('No issues with identical issue numbering were detected for this series')
mc_issuenumber = None
else:
logger.fdebug('Multiple issues with identical numbering were detected. Attempting to accomodate.')
for mc in multiple_check:
mc_issuenumber.append({"Int_IssueNumber": mc['Int_IssueNumber']})
if not mc_issuenumber is None:
for mciss in mc_issuenumber:
mchk = myDB.select('SELECT * FROM issues WHERE ComicID=? AND Int_IssueNumber=?', [ComicID, mciss['Int_IssueNumber']])
for mck in mchk:
mc_issue.append({"Int_IssueNumber": mck['Int_IssueNumber'],
"IssueYear": mck['IssueDate'][:4],
"IssueID": mck['IssueID']})
mc_annual = []
mc_annualnumber = []
if mylar.CONFIG.ANNUALS_ON:
mult_ann_check = myDB.select('SELECT * FROM annuals WHERE ComicID=? GROUP BY Int_IssueNumber HAVING (COUNT(Int_IssueNumber) > 1)', [ComicID])
if len(mult_ann_check) == 0:
logger.fdebug('[ANNUAL-CHK] No annuals with identical issue numbering across annual volumes were detected for this series')
mc_annualnumber = None
else:
logger.fdebug('[ANNUAL-CHK] Multiple issues with identical numbering were detected across multiple annual volumes. Attempting to accomodate.')
for mc in mult_ann_check:
mc_annualnumber.append({"Int_IssueNumber": mc['Int_IssueNumber']})
if not mc_annualnumber is None:
for mcann in mc_annualnumber:
achk = myDB.select('SELECT * FROM annuals WHERE ComicID=? AND Int_IssueNumber=?', [ComicID, mcann['Int_IssueNumber']])
for ack in achk:
mc_annual.append({"Int_IssueNumber": ack['Int_IssueNumber'],
"IssueYear": ack['IssueDate'][:4],
"IssueID": ack['IssueID'],
"ReleaseComicID": ack['ReleaseComicID']})
#logger.fdebug('mc_issue:' + str(mc_issue))
#logger.fdebug('mc_annual:' + str(mc_annual))
issID_to_ignore = []
issID_to_ignore.append(str(ComicID))
issID_to_write = []
ANNComicID = None
reissues = myDB.select('SELECT * FROM issues WHERE ComicID=?', [ComicID])
while (fn < fccnt):
haveissue = "no"
issuedupe = "no"
annualdupe = "no"
try:
tmpfc = fc['comiclist'][fn]
except IndexError:
logger.fdebug(module + ' Unable to properly retrieve a file listing for the given series.')
logger.fdebug(module + ' Probably because the filenames being scanned are not in a parseable format')
if fn == 0:
return
else:
break
if tmpfc['JusttheDigits'] is not None:
temploc= tmpfc['JusttheDigits'].replace('_', ' ')
temploc = re.sub('[\#\']', '', temploc)
logger.fdebug('temploc: %s' % temploc)
else:
#assume 1 if not given
if any([booktype == 'TPB', booktype == 'One-Shot']):
temploc = '1'
else:
temploc = None
logger.warn('The filename [%s] does not have a valid issue number, and the Edition of the series is %s. You might need to Forcibly Mark the Series as TPB/GN and try this again.' % (tmpfc['ComicFilename'], rescan['Type']))
return
if all(['annual' not in temploc.lower(), 'special' not in temploc.lower()]):
#remove the extension here
extensions = ('.cbr', '.cbz', '.cb7')
if temploc.lower().endswith(extensions):
logger.fdebug(module + ' Removed extension for issue: ' + temploc)
temploc = temploc[:-4]
fcnew_af = re.findall('[^\()]+', temploc)
fcnew = shlex.split(fcnew_af[0])
fcn = len(fcnew)
n = 0
while True:
try:
reiss = reissues[n]
int_iss = None
except IndexError:
break
int_iss = helpers.issuedigits(reiss['Issue_Number'])
issyear = reiss['IssueDate'][:4]
old_status = reiss['Status']
issname = reiss['IssueName']
fnd_iss_except = 'None'
if temploc is not None:
fcdigit = helpers.issuedigits(temploc)
elif any([booktype == 'TPB', booktype == 'One-Shot']) and temploc is None:
fcdigit = helpers.issuedigits('1')
if int(fcdigit) == int_iss:
logger.fdebug(module + ' [' + str(reiss['IssueID']) + '] Issue match - fcdigit: ' + str(fcdigit) + ' ... int_iss: ' + str(int_iss))
if '-' in temploc and temploc.find(reiss['Issue_Number']) > temploc.find('-'):
logger.fdebug(module + ' I have detected a possible Title in the filename')
logger.fdebug(module + ' the issue # has occured after the -, so I assume that it is part of the Title')
break
#baseline these to default to normal scanning
multiplechk = False
issuedupe = "no"
foundchk = False
#check here if muliple identical numbering issues exist for the series
if len(mc_issue) > 1:
for mi in mc_issue:
if mi['Int_IssueNumber'] == int_iss:
if mi['IssueID'] == reiss['IssueID']:
logger.fdebug(module + ' IssueID matches to multiple issues : ' + str(mi['IssueID']) + '. Checking dupe.')
logger.fdebug(module + ' miISSUEYEAR: ' + str(mi['IssueYear']) + ' -- issyear : ' + str(issyear))
if any(mi['IssueID'] == d['issueid'] for d in issuedupechk):
logger.fdebug(module + ' IssueID already within dupe. Checking next if available.')
multiplechk = True
break
if (mi['IssueYear'] in tmpfc['ComicFilename']) and (issyear == mi['IssueYear']):
logger.fdebug(module + ' Matched to year within filename : ' + str(issyear))
multiplechk = False
break
else:
logger.fdebug(module + ' Did not match to year within filename : ' + str(issyear))
multiplechk = True
if multiplechk == True:
n+=1
continue
#this will detect duplicate filenames within the same directory.
for di in issuedupechk:
if di['fcdigit'] == fcdigit and di['issueid'] == reiss['IssueID']:
#base off of config - base duplication keep on filesize or file-type (or both)
logger.fdebug('[DUPECHECK] Duplicate issue detected [' + di['filename'] + '] [' + tmpfc['ComicFilename'] + ']')
# mylar.CONFIG.DUPECONSTRAINT = 'filesize' / 'filetype-cbr' / 'filetype-cbz'
logger.fdebug('[DUPECHECK] Based on duplication preferences I will retain based on : ' + mylar.CONFIG.DUPECONSTRAINT)
removedupe = False
if 'cbr' in mylar.CONFIG.DUPECONSTRAINT or 'cbz' in mylar.CONFIG.DUPECONSTRAINT:
if 'cbr' in mylar.CONFIG.DUPECONSTRAINT:
#this has to be configured in config - either retain cbr or cbz.
if tmpfc['ComicFilename'].endswith('.cbz'):
#keep di['filename']
logger.fdebug('[DUPECHECK-CBR PRIORITY] [#' + reiss['Issue_Number'] + '] Retaining currently scanned in file : ' + di['filename'])
issuedupe = "yes"
break
else:
#keep tmpfc['ComicFilename']
logger.fdebug('[DUPECHECK-CBR PRIORITY] [#' + reiss['Issue_Number'] + '] Retaining newly scanned in file : ' + tmpfc['ComicFilename'])
removedupe = True
elif 'cbz' in mylar.CONFIG.DUPECONSTRAINT:
if tmpfc['ComicFilename'].endswith('.cbr'):
#keep di['filename']
logger.fdebug('[DUPECHECK-CBZ PRIORITY] [#' + reiss['Issue_Number'] + '] Retaining currently scanned in filename : ' + di['filename'])
issuedupe = "yes"
break
else:
#keep tmpfc['ComicFilename']
logger.fdebug('[DUPECHECK-CBZ PRIORITY] [#' + reiss['Issue_Number'] + '] Retaining newly scanned in filename : ' + tmpfc['ComicFilename'])
removedupe = True
if mylar.CONFIG.DUPECONSTRAINT == 'filesize':
if tmpfc['ComicSize'] <= di['filesize']:
logger.fdebug('[DUPECHECK-FILESIZE PRIORITY] [#' + reiss['Issue_Number'] + '] Retaining currently scanned in filename : ' + di['filename'])
issuedupe = "yes"
break
else:
logger.fdebug('[DUPECHECK-FILESIZE PRIORITY] [#' + reiss['Issue_Number'] + '] Retaining newly scanned in filename : ' + tmpfc['ComicFilename'])
removedupe = True
if removedupe:
#need to remove the entry from issuedupechk so can add new one.
#tuple(y for y in x if y) for x in a
issuedupe_temp = []
tmphavefiles = 0
for x in issuedupechk:
#logger.fdebug('Comparing x: ' + x['filename'] + ' to di:' + di['filename'])
if x['filename'] != di['filename']:
#logger.fdebug('Matched.')
issuedupe_temp.append(x)
tmphavefiles+=1
issuedupechk = issuedupe_temp
havefiles = tmphavefiles + len(annualdupechk)
foundchk = False
break
if issuedupe == "no":
if foundchk == False:
logger.fdebug(module + ' Matched...issue: ' + rescan['ComicName'] + '#' + reiss['Issue_Number'] + ' --- ' + str(int_iss))
havefiles+=1
haveissue = "yes"
isslocation = helpers.conversion(tmpfc['ComicFilename'])
issSize = str(tmpfc['ComicSize'])
logger.fdebug(module + ' .......filename: ' + isslocation)
logger.fdebug(module + ' .......filesize: ' + str(tmpfc['ComicSize']))
# to avoid duplicate issues which screws up the count...let's store the filename issues then
# compare earlier...
issuedupechk.append({'fcdigit': fcdigit,
'filename': tmpfc['ComicFilename'],
'filesize': tmpfc['ComicSize'],
'issueyear': issyear,
'issueid': reiss['IssueID']})
break
if issuedupe == "yes":
logger.fdebug(module + ' I should break out here because of a dupe.')
break
if haveissue == "yes" or issuedupe == "yes": break
n+=1
else:
if tmpfc['AnnualComicID']:
ANNComicID = tmpfc['AnnualComicID']
logger.fdebug(module + ' Forcing ComicID to ' + str(ANNComicID) + ' in case of duplicate numbering across volumes.')
reannuals = myDB.select('SELECT * FROM annuals WHERE ComicID=? AND ReleaseComicID=?', [ComicID, ANNComicID])
else:
reannuals = myDB.select('SELECT * FROM annuals WHERE ComicID=?', [ComicID])
ANNComicID = ComicID
if len(reannuals) == 0:
#it's possible if annual integration is enabled, and an annual series is added directly to the wachlist,
#not as part of a series, that the above won't work since it's looking in the wrong table.
reannuals = myDB.select('SELECT * FROM issues WHERE ComicID=?', [ComicID])
ANNComicID = None #need to set this to None so we write to the issues table and not the annuals
# annual inclusion here.
#logger.fdebug("checking " + str(temploc))
fcnew = shlex.split(str(temploc))
fcn = len(fcnew)
n = 0
reann = None
while True:
try:
reann = reannuals[n]
except IndexError:
break
int_iss = helpers.issuedigits(reann['Issue_Number'])
#logger.fdebug(module + ' int_iss:' + str(int_iss))
issyear = reann['IssueDate'][:4]
old_status = reann['Status']
fcdigit = helpers.issuedigits(re.sub('annual', '', temploc.lower()).strip())
if fcdigit == 999999999999999:
fcdigit = helpers.issuedigits(re.sub('special', '', temploc.lower()).strip())
if int(fcdigit) == int_iss and ANNComicID is not None:
logger.fdebug(module + ' [' + str(ANNComicID) + '] Annual match - issue : ' + str(int_iss))
#baseline these to default to normal scanning
multiplechk = False
annualdupe = "no"
foundchk = False
#check here if muliple identical numbering issues exist for the series
if len(mc_annual) > 1:
for ma in mc_annual:
if ma['Int_IssueNumber'] == int_iss:
if ma['IssueID'] == reann['IssueID']:
logger.fdebug(module + ' IssueID matches to multiple issues : ' + str(ma['IssueID']) + '. Checking dupe.')
logger.fdebug(module + ' maISSUEYEAR: ' + str(ma['IssueYear']) + ' -- issyear : ' + str(issyear))
if any(ma['IssueID'] == d['issueid'] for d in annualdupechk):
logger.fdebug(module + ' IssueID already within dupe. Checking next if available.')
multiplechk = True
break
if (ma['IssueYear'] in tmpfc['ComicFilename']) and (issyear == ma['IssueYear']):
logger.fdebug(module + ' Matched to year within filename : ' + str(issyear))
multiplechk = False
ANNComicID = ack['ReleaseComicID']
break
else:
logger.fdebug(module + ' Did not match to year within filename : ' + str(issyear))
multiplechk = True
if multiplechk == True:
n+=1
continue
#this will detect duplicate filenames within the same directory.
for di in annualdupechk:
if di['fcdigit'] == fcdigit and di['issueid'] == reann['IssueID']:
#base off of config - base duplication keep on filesize or file-type (or both)
logger.fdebug('[DUPECHECK] Duplicate issue detected [' + di['filename'] + '] [' + tmpfc['ComicFilename'] + ']')
# mylar.CONFIG.DUPECONSTRAINT = 'filesize' / 'filetype-cbr' / 'filetype-cbz'
logger.fdebug('[DUPECHECK] Based on duplication preferences I will retain based on : ' + mylar.CONFIG.DUPECONSTRAINT)
removedupe = False
if 'cbr' in mylar.CONFIG.DUPECONSTRAINT or 'cbz' in mylar.CONFIG.DUPECONSTRAINT:
if 'cbr' in mylar.CONFIG.DUPECONSTRAINT:
#this has to be configured in config - either retain cbr or cbz.
if tmpfc['ComicFilename'].endswith('.cbz'):
#keep di['filename']
logger.fdebug('[DUPECHECK-CBR PRIORITY] [#' + reann['Issue_Number'] + '] Retaining currently scanned in file : ' + di['filename'])
annualdupe = "yes"
break
else:
#keep tmpfc['ComicFilename']
logger.fdebug('[DUPECHECK-CBR PRIORITY] [#' + reann['Issue_Number'] + '] Retaining newly scanned in file : ' + tmpfc['ComicFilename'])
removedupe = True
elif 'cbz' in mylar.CONFIG.DUPECONSTRAINT:
if tmpfc['ComicFilename'].endswith('.cbr'):
#keep di['filename']
logger.fdebug('[DUPECHECK-CBZ PRIORITY] [#' + reann['Issue_Number'] + '] Retaining currently scanned in filename : ' + di['filename'])
annualdupe = "yes"
break
else:
#keep tmpfc['ComicFilename']
logger.fdebug('[DUPECHECK-CBZ PRIORITY] [#' + reann['Issue_Number'] + '] Retaining newly scanned in filename : ' + tmpfc['ComicFilename'])
removedupe = True
if mylar.CONFIG.DUPECONSTRAINT == 'filesize':
if tmpfc['ComicSize'] <= di['filesize']:
logger.fdebug('[DUPECHECK-FILESIZE PRIORITY] [#' + reann['Issue_Number'] + '] Retaining currently scanned in filename : ' + di['filename'])
annualdupe = "yes"
break
else:
logger.fdebug('[DUPECHECK-FILESIZE PRIORITY] [#' + reann['Issue_Number'] + '] Retaining newly scanned in filename : ' + tmpfc['ComicFilename'])
removedupe = True
if removedupe:
#need to remove the entry from issuedupechk so can add new one.
#tuple(y for y in x if y) for x in a
annualdupe_temp = []
tmphavefiles = 0
for x in annualdupechk:
logger.fdebug('Comparing x: ' + x['filename'] + ' to di:' + di['filename'])
if x['filename'] != di['filename']:
annualdupe_temp.append(x)
tmphavefiles+=1
annualdupechk = annualdupe_temp
havefiles = tmphavefiles + len(issuedupechk)
foundchk = False
break
if annualdupe == "no":
if foundchk == False:
logger.fdebug(module + ' Matched...annual issue: ' + rescan['ComicName'] + '#' + str(reann['Issue_Number']) + ' --- ' + str(int_iss))
havefiles+=1
haveissue = "yes"
isslocation = helpers.conversion(tmpfc['ComicFilename'])
issSize = str(tmpfc['ComicSize'])
logger.fdebug(module + ' .......filename: ' + isslocation)
logger.fdebug(module + ' .......filesize: ' + str(tmpfc['ComicSize']))
# to avoid duplicate issues which screws up the count...let's store the filename issues then
# compare earlier...
annualdupechk.append({'fcdigit': int(fcdigit),
'anncomicid': ANNComicID,
'filename': tmpfc['ComicFilename'],
'filesize': tmpfc['ComicSize'],
'issueyear': issyear,
'issueid': reann['IssueID']})
break
if annualdupe == "yes":
logger.fdebug(module + ' I should break out here because of a dupe.')
break
if haveissue == "yes" or annualdupe == "yes": break
n+=1
if issuedupe == "yes" or annualdupe == "yes": pass
else:
#we have the # of comics, now let's update the db.
#even if we couldn't find the physical issue, check the status.
#-- if annuals aren't enabled, this will bugger out.
writeit = True
try:
if mylar.CONFIG.ANNUALS_ON:
if any(['annual' in temploc.lower(), 'special' in temploc.lower()]):
if reann is None:
logger.fdebug(module + ' Annual/Special present in location, but series does not have any annuals attached to it - Ignoring')
writeit = False
else:
iss_id = reann['IssueID']
else:
iss_id = reiss['IssueID']
else:
if any(['annual' in temploc.lower(), 'special' in temploc.lower()]):
logger.fdebug(module + ' Annual support not enabled, but annual/special issue present within directory. Ignoring issue.')
writeit = False
else:
iss_id = reiss['IssueID']
except:
logger.warn(module + ' An error occured trying to get the relevant issue data. This is probably due to the series not having proper issue data.')
logger.warn(module + ' you should either Refresh the series, and/or submit an issue on github in regards to the series and the error.')
return
if writeit == True and haveissue == 'yes':
#logger.fdebug(module + ' issueID to write to db:' + str(iss_id))
controlValueDict = {"IssueID": str(iss_id)}
#if Archived, increase the 'Have' count.
if archive:
issStatus = "Archived"
else:
issStatus = "Downloaded"
newValueDict = {"Location": isslocation,
"ComicSize": issSize,
"Status": issStatus
}
issID_to_ignore.append(str(iss_id))
if ANNComicID:
myDB.upsert("annuals", newValueDict, controlValueDict)
ANNComicID = None
else:
myDB.upsert("issues", newValueDict, controlValueDict)
else:
ANNComicID = None
fn+=1
#here we need to change the status of the ones we DIDN'T FIND above since the loop only hits on FOUND issues.
update_iss = []
#break this up in sequnces of 200 so it doesn't break the sql statement.
cnt = 0
for genlist in helpers.chunker(issID_to_ignore, 200):
tmpsql = "SELECT * FROM issues WHERE ComicID=? AND IssueID not in ({seq})".format(seq=','.join(['?'] *(len(genlist) -1)))
chkthis = myDB.select(tmpsql, genlist)
if chkthis is None:
pass
else:
for chk in chkthis:
if chk['IssueID'] in issID_to_ignore:
continue
old_status = chk['Status']
if old_status == "Skipped":
if mylar.CONFIG.AUTOWANT_ALL:
issStatus = "Wanted"
else:
issStatus = "Skipped"
#elif old_status == "Archived":
# issStatus = "Archived"
elif old_status == "Downloaded":
issStatus = "Archived"
else:
continue
#elif old_status == "Wanted":
# issStatus = "Wanted"
#elif old_status == "Ignored":
# issStatus = "Ignored"
#elif old_status == "Snatched": #this is needed for torrents, or else it'll keep on queuing..
# issStatus = "Snatched"
#else:
# issStatus = "Skipped"
update_iss.append({"IssueID": chk['IssueID'],
"Status": issStatus})
if len(update_iss) > 0:
i = 0
#do it like this to avoid DB locks...
for ui in update_iss:
controlValueDict = {"IssueID": ui['IssueID']}
newStatusValue = {"Status": ui['Status']}
myDB.upsert("issues", newStatusValue, controlValueDict)
i+=1
logger.info(module + ' Updated the status of ' + str(i) + ' issues for ' + rescan['ComicName'] + ' (' + str(rescan['ComicYear']) + ') that were not found.')
logger.info(module + ' Total files located: ' + str(havefiles))
foundcount = havefiles
arcfiles = 0
arcanns = 0
# if filechecker returns 0 files (it doesn't find any), but some issues have a status of 'Archived'
# the loop below won't work...let's adjust :)
arcissues = myDB.select("SELECT count(*) FROM issues WHERE ComicID=? and Status='Archived'", [ComicID])
if int(arcissues[0][0]) > 0:
arcfiles = arcissues[0][0]
arcannuals = myDB.select("SELECT count(*) FROM annuals WHERE ComicID=? and Status='Archived'", [ComicID])
if int(arcannuals[0][0]) > 0:
arcanns = arcannuals[0][0]
if havefiles == 0:
if arcfiles > 0 or arcanns > 0:
arcfiles = arcfiles + arcanns
havefiles = havefiles + arcfiles
logger.fdebug(module + ' Adjusting have total to ' + str(havefiles) + ' because of this many archive files already in Archive status :' + str(arcfiles))
else:
#if files exist in the given directory, but are in an archived state - the numbers will get botched up here.
if (arcfiles + arcanns) > 0:
logger.fdebug(module + ' ' + str(int(arcfiles + arcanns)) + ' issue(s) are in an Archive status already. Increasing Have total from ' + str(havefiles) + ' to include these archives.')
havefiles = havefiles + (arcfiles + arcanns)
ignorecount = 0
if mylar.CONFIG.IGNORE_HAVETOTAL: # if this is enabled, will increase Have total as if in Archived Status
ignoresi = myDB.select("SELECT count(*) FROM issues WHERE ComicID=? AND Status='Ignored'", [ComicID])
ignoresa = myDB.select("SELECT count(*) FROM annuals WHERE ComicID=? AND Status='Ignored'", [ComicID])
ignorecount = int(ignoresi[0][0]) + int(ignoresa[0][0])
if ignorecount > 0:
havefiles = havefiles + ignorecount
logger.fdebug(module + ' Adjusting have total to ' + str(havefiles) + ' because of this many Ignored files:' + str(ignorecount))
snatchedcount = 0
if mylar.CONFIG.SNATCHED_HAVETOTAL: # if this is enabled, will increase Have total as if in Archived Status
snatches = myDB.select("SELECT count(*) FROM issues WHERE ComicID=? AND Status='Snatched'", [ComicID])
if int(snatches[0][0]) > 0:
snatchedcount = snatches[0][0]
havefiles = havefiles + snatchedcount
logger.fdebug(module + ' Adjusting have total to ' + str(havefiles) + ' because of this many Snatched files:' + str(snatchedcount))
#now that we are finished...
#adjust for issues that have been marked as Downloaded, but aren't found/don't exist.
#do it here, because above loop only cycles though found comics using filechecker.
downissues = myDB.select("SELECT * FROM issues WHERE ComicID=? and Status='Downloaded'", [ComicID])
downissues += myDB.select("SELECT * FROM annuals WHERE ComicID=? and Status='Downloaded'", [ComicID])
if downissues is None:
pass
else:
archivedissues = 0 #set this to 0 so it tallies correctly.
for down in downissues:
#print "downlocation:" + str(down['Location'])
#remove special characters from
#temploc = rescan['ComicLocation'].replace('_', ' ')
#temploc = re.sub('[\#\'\/\.]', '', temploc)
#print ("comiclocation: " + str(rescan['ComicLocation']))
#print ("downlocation: " + str(down['Location']))
if down['Location'] is None:
logger.fdebug(module + ' Location does not exist which means file was not downloaded successfully, or was moved.')
controlValue = {"IssueID": down['IssueID']}
newValue = {"Status": "Archived"}
myDB.upsert("issues", newValue, controlValue)
archivedissues+=1
pass
else:
comicpath = os.path.join(rescan['ComicLocation'], down['Location'])
if os.path.exists(comicpath):
continue
logger.fdebug('Issue exists - no need to change status.')
else:
if mylar.CONFIG.MULTIPLE_DEST_DIRS is not None and mylar.CONFIG.MULTIPLE_DEST_DIRS != 'None':
if os.path.exists(os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(rescan['ComicLocation']))):
#logger.fdebug('Issue(s) currently exist and found within multiple destination directory location')
continue
#print "Changing status from Downloaded to Archived - cannot locate file"
controlValue = {"IssueID": down['IssueID']}
newValue = {"Status": "Archived"}
myDB.upsert("issues", newValue, controlValue)
archivedissues+=1
if archivedissues > 0:
logger.fdebug(module + ' I have changed the status of ' + str(archivedissues) + ' issues to a status of Archived, as I now cannot locate them in the series directory.')
havefiles = havefiles + archivedissues #arcfiles already tallied in havefiles in above segment
#combined total for dispay total purposes only.
combined_total = iscnt + anncnt
if mylar.CONFIG.IGNORE_TOTAL: # if this is enabled, will increase Have total as if in Archived Status
ignoresa = myDB.select("SELECT count(*) FROM issues WHERE ComicID=? AND Status='Ignored'", [ComicID])
ignoresb = myDB.select("SELECT count(*) FROM annuals WHERE ComicID=? AND Status='Ignored'", [ComicID])
ignorecnt = ignoresa[0][0] + ignoresb[0][0]
if ignorecnt > 0:
combined_total -= ignorecnt
logger.fdebug('%s Reducing total comics in series from %s to %s because of %s ignored files.' % (module, (iscnt+anncnt), combined_total, ignorecnt))
#quick check
if havefiles > combined_total:
logger.warn(module + ' It looks like you have physical issues in the series directory, but are forcing these issues to an Archived Status. Adjusting have counts.')
havefiles = havefiles - arcfiles
thetotals = totals(ComicID, havefiles, combined_total, module, recheck=recheck)
totalarc = arcfiles + archivedissues
#enforce permissions
if mylar.CONFIG.ENFORCE_PERMS:
logger.fdebug(module + ' Ensuring permissions/ownership enforced for series: ' + rescan['ComicName'])
filechecker.setperms(rescan['ComicLocation'])
logger.info(module + ' I have physically found ' + str(foundcount) + ' issues, ignored ' + str(ignorecount) + ' issues, snatched ' + str(snatchedcount) + ' issues, and accounted for ' + str(totalarc) + ' in an Archived state [ Total Issue Count: ' + str(havefiles) + ' / ' + str(combined_total) + ' ]')
def totals(ComicID, havefiles=None, totalfiles=None, module=None, issueid=None, file=None, recheck=False):
if module is None:
module = '[FILE-RESCAN]'
myDB = db.DBConnection()
filetable = 'issues'
if any([havefiles is None, havefiles == '+1']):
if havefiles is None:
hf = myDB.selectone("SELECT Have, Total FROM comics WHERE ComicID=?", [ComicID]).fetchone()
havefiles = int(hf['Have'])
totalfiles = int(hf['Total'])
else:
hf = myDB.selectone("SELECT a.Have, a.Total, b.Status as IssStatus FROM comics AS a INNER JOIN issues as b ON a.ComicID=b.ComicID WHERE b.IssueID=?", [issueid]).fetchone()
if hf is None:
hf = myDB.selectone("SELECT a.Have, a.Total, b.Status as IssStatus FROM comics AS a INNER JOIN annuals as b ON a.ComicID=b.ComicID WHERE b.IssueID=?", [issueid]).fetchone()
filetable = 'annuals'
totalfiles = int(hf['Total'])
logger.fdebug('totalfiles: %s' % totalfiles)
logger.fdebug('status: %s' % hf['IssStatus'])
if hf['IssStatus'] != 'Downloaded':
try:
havefiles = int(hf['Have']) +1
if havefiles > totalfiles and recheck is False:
recheck = True
return forceRescan(ComicID, recheck=recheck)
except TypeError:
if totalfiles == 1:
havefiles = 1
else:
logger.warn('Total issues for this series [ComiciD:%s/IssueID:%s] is not 1 when it should be. This is probably a mistake and the series should be refreshed.' % (ComicID, issueid))
havefiles = 0
logger.fdebug('incremented havefiles: %s' % havefiles)
else:
havefiles = int(hf['Have'])
logger.fdebug('untouched havefiles: %s' % havefiles)
#let's update the total count of comics that was found.
#store just the total of issues, since annuals gets tracked seperately.
controlValueStat = {"ComicID": ComicID}
newValueStat = {"Have": havefiles,
"Total": totalfiles}
myDB.upsert("comics", newValueStat, controlValueStat)
if file is not None:
controlValueStat = {"IssueID": issueid,
"ComicID": ComicID}
newValueStat = {"ComicSize": os.path.getsize(file)}
myDB.upsert(filetable, newValueStat, controlValueStat)
| 92,033 | Python | .py | 1,480 | 43.868243 | 332 | 0.525141 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,258 | weeklypullit.py | evilhero_mylar/mylar/weeklypullit.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import mylar
from mylar import logger, helpers, weeklypull
class Weekly():
def __init__(self):
pass
def run(self):
logger.info('[WEEKLY] Checking Weekly Pull-list for new releases/updates')
helpers.job_management(write=True, job='Weekly Pullist', current_run=helpers.utctimestamp(), status='Running')
mylar.WEEKLY_STATUS = 'Running'
weeklypull.pullit()
weeklypull.future_check()
helpers.job_management(write=True, job='Weekly Pullist', last_run_completed=helpers.utctimestamp(), status='Waiting')
mylar.WEEKLY_STATUS = 'Waiting'
| 1,290 | Python | .py | 28 | 42.285714 | 125 | 0.738057 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,259 | wwt.py | evilhero_mylar/mylar/wwt.py | #!/usr/bin/env python
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import requests
from bs4 import BeautifulSoup, UnicodeDammit
import urlparse
import re
import time
import sys
import datetime
from datetime import timedelta
import lib.cfscrape as cfscrape
import mylar
from mylar import logger, helpers
class wwt(object):
def __init__(self, name, issue):
self.url = mylar.WWTURL
self.query = name + ' ' + str(int(issue)) #'Batman White Knight'
logger.info('query set to : %s' % self.query)
pass
def wwt_connect(self):
resultlist = None
params = {'c50': 1,
'search': self.query,
'cat': 132,
'incldead': 0,
'lang': 0}
with cfscrape.create_scraper() as s:
newurl = self.url + 'torrents-search.php'
if mylar.WWT_CF_COOKIEVALUE is None:
cf_cookievalue, cf_user_agent = s.get_tokens(newurl, user_agent=mylar.CV_HEADERS['User-Agent'])
mylar.WWT_CF_COOKIEVALUE = cf_cookievalue
r = s.get(newurl, params=params, verify=True, cookies=mylar.WWT_CF_COOKIEVALUE, headers=mylar.CV_HEADERS)
if not r.status_code == 200:
return
logger.info('status code: %s' % r.status_code)
soup = BeautifulSoup(r.content, "html5lib")
resultpages = soup.find("p", {"align": "center"})
try:
pagelist = resultpages.findAll("a")
except:
logger.info('No results found for %s' % self.query)
return
pages = []
for p in pagelist:
if p['href'] not in pages:
logger.fdebug('page: %s' % p['href'])
pages.append(p['href'])
logger.fdebug('pages: %s' % (len(pages) + 1))
resultlist = self.wwt_data(soup)
if pages:
for p in pages:
time.sleep(5) #5s delay btwn requests
newurl = self.url + str(p)
r = s.get(newurl, params=params, verify=True)
if not r.status_code == 200:
continue
soup = BeautifulSoup(r.content, "html5lib")
resultlist += self.wwt_data(soup)
logger.fdebug('%s results: %s' % (len(resultlist), resultlist))
res = {}
if len(resultlist) >= 1:
res['entries'] = resultlist
return res
def wwt_data(self, data):
resultw = data.find("table", {"class": "w3-table w3-striped w3-bordered w3-card-4"})
resultp = resultw.findAll("tr")
#final = []
results = []
for res in resultp:
if res.findNext(text=True) == 'Torrents Name':
continue
title = res.find('a')
torrent = title['title']
try:
for link in res.find_all('a', href=True):
if link['href'].startswith('download.php'):
linkurl = urlparse.parse_qs(urlparse.urlparse(link['href']).query)['id']
#results = {'torrent': torrent,
# 'link': link['href']}
break
for td in res.findAll('td'):
try:
seed = td.find("font", {"color": "green"})
leech = td.find("font", {"color": "#ff0000"})
value = td.findNext(text=True)
if any(['MB' in value, 'GB' in value]):
if 'MB' in value:
szform = 'MB'
sz = 'M'
else:
szform = 'GB'
sz = 'G'
size = helpers.human2bytes(str(re.sub(szform, '', value)).strip() + sz)
elif seed is not None:
seeders = value
#results['seeders'] = seeders
elif leech is not None:
leechers = value
#results['leechers'] = leechers
else:
age = value
#results['age'] = age
except Exception as e:
logger.warn('exception: %s' % e)
logger.info('age: %s' % age)
results.append({'title': torrent,
'link': ''.join(linkurl),
'pubdate': self.string_to_delta(age),
'size': size,
'site': 'WWT'})
logger.info('results: %s' % results)
except Exception as e:
logger.warn('Error: %s' % e)
continue
#else:
# final.append(results)
return results
def string_to_delta(self, relative):
#using simplistic year (no leap months are 30 days long.
#WARNING: 12 months != 1 year
logger.info('trying to remap date from %s' % relative)
unit_mapping = [('mic', 'microseconds', 1),
('millis', 'microseconds', 1000),
('sec', 'seconds', 1),
('mins', 'seconds', 60),
('hrs', 'seconds', 3600),
('day', 'days', 1),
('wk', 'days', 7),
('mon', 'days', 30),
('year', 'days', 365)]
try:
tokens = relative.lower().split(' ')
past = False
if tokens[-1] == 'ago':
past = True
tokens = tokens[:-1]
elif tokens[0] == 'in':
tokens = tokens[1:]
units = dict(days = 0, seconds = 0, microseconds = 0)
#we should always get pairs, if not we let this die and throw an exception
while len(tokens) > 0:
value = tokens.pop(0)
if value == 'and': #just skip this token
continue
else:
value = float(value)
unit = tokens.pop(0)
for match, time_unit, time_constant in unit_mapping:
if unit.startswith(match):
units[time_unit] += value * time_constant
#print datetime.timedelta(**units), past
val = datetime.datetime.now() - datetime.timedelta(**units)
return datetime.datetime.strftime(val, '%a, %d %b %Y %H:%M:%S')
except Exception as e:
raise ValueError("Don't know how to parse %s: %s" % (relative, e))
| 7,717 | Python | .py | 168 | 29.416667 | 117 | 0.466986 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,260 | cv.py | evilhero_mylar/mylar/cv.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import sys
import os
import re
import time
import logger
import string
import urllib2
import lib.feedparser
import mylar
import platform
from bs4 import BeautifulSoup as Soup
from xml.parsers.expat import ExpatError
import httplib
import requests
def patch_http_response_read(func):
def inner(*args):
try:
return func(*args)
except httplib.IncompleteRead, e:
return e.partial
return inner
httplib.HTTPResponse.read = patch_http_response_read(httplib.HTTPResponse.read)
if platform.python_version() == '2.7.6':
httplib.HTTPConnection._http_vsn = 10
httplib.HTTPConnection._http_vsn_str = 'HTTP/1.0'
def pulldetails(comicid, type, issueid=None, offset=1, arclist=None, comicidlist=None):
#import easy to use xml parser called minidom:
from xml.dom.minidom import parseString
if mylar.CONFIG.COMICVINE_API == 'None' or mylar.CONFIG.COMICVINE_API is None:
logger.warn('You have not specified your own ComicVine API key - it\'s a requirement. Get your own @ http://api.comicvine.com.')
return
else:
comicapi = mylar.CONFIG.COMICVINE_API
if type == 'comic':
if not comicid.startswith('4050-'): comicid = '4050-' + comicid
PULLURL = mylar.CVURL + 'volume/' + str(comicid) + '/?api_key=' + str(comicapi) + '&format=xml&field_list=name,count_of_issues,issues,start_year,site_detail_url,image,publisher,description,first_issue,deck,aliases'
elif type == 'issue':
if mylar.CONFIG.CV_ONLY:
cv_type = 'issues'
if arclist is None:
searchset = 'filter=volume:' + str(comicid) + '&field_list=cover_date,description,id,image,issue_number,name,date_last_updated,store_date'
else:
searchset = 'filter=id:' + (arclist) + '&field_list=cover_date,id,issue_number,name,date_last_updated,store_date,volume'
else:
cv_type = 'volume/' + str(comicid)
searchset = 'name,count_of_issues,issues,start_year,site_detail_url,image,publisher,description,store_date'
PULLURL = mylar.CVURL + str(cv_type) + '/?api_key=' + str(comicapi) + '&format=xml&' + str(searchset) + '&offset=' + str(offset)
elif any([type == 'image', type == 'firstissue']):
#this is used ONLY for CV_ONLY
PULLURL = mylar.CVURL + 'issues/?api_key=' + str(comicapi) + '&format=xml&filter=id:' + str(issueid) + '&field_list=cover_date,image'
elif type == 'storyarc':
PULLURL = mylar.CVURL + 'story_arcs/?api_key=' + str(comicapi) + '&format=xml&filter=name:' + str(issueid) + '&field_list=cover_date'
elif type == 'comicyears':
PULLURL = mylar.CVURL + 'volumes/?api_key=' + str(comicapi) + '&format=xml&filter=id:' + str(comicidlist) + '&field_list=name,id,start_year,publisher,description,deck,aliases&offset=' + str(offset)
elif type == 'import':
PULLURL = mylar.CVURL + 'issues/?api_key=' + str(comicapi) + '&format=xml&filter=id:' + (comicidlist) + '&field_list=cover_date,id,issue_number,name,date_last_updated,store_date,volume' + '&offset=' + str(offset)
elif type == 'update_dates':
PULLURL = mylar.CVURL + 'issues/?api_key=' + str(comicapi) + '&format=xml&filter=id:' + (comicidlist)+ '&field_list=date_last_updated, id, issue_number, store_date, cover_date, name, volume ' + '&offset=' + str(offset)
#logger.info('CV.PULLURL: ' + PULLURL)
#new CV API restriction - one api request / second.
if mylar.CONFIG.CVAPI_RATE is None or mylar.CONFIG.CVAPI_RATE < 2:
time.sleep(2)
else:
time.sleep(mylar.CONFIG.CVAPI_RATE)
#download the file:
#set payload to None for now...
payload = None
try:
r = requests.get(PULLURL, params=payload, verify=mylar.CONFIG.CV_VERIFY, headers=mylar.CV_HEADERS)
except Exception, e:
logger.warn('Error fetching data from ComicVine: %s' % (e))
return
#logger.fdebug('cv status code : ' + str(r.status_code))
try:
dom = parseString(r.content)
except ExpatError:
if u'<title>Abnormal Traffic Detected' in r.content:
logger.error('ComicVine has banned this server\'s IP address because it exceeded the API rate limit.')
else:
logger.warn('[WARNING] ComicVine is not responding correctly at the moment. This is usually due to some problems on their end. If you re-try things again in a few moments, things might work')
return
except Exception as e:
logger.warn('[ERROR] Error returned from CV: %s' % e)
return
else:
return dom
def getComic(comicid, type, issueid=None, arc=None, arcid=None, arclist=None, comicidlist=None):
if type == 'issue':
offset = 1
issue = {}
ndic = []
issuechoice = []
comicResults = []
firstdate = '2099-00-00'
#let's find out how many results we get from the query...
if comicid is None:
#if comicid is None, it's coming from the story arc search results.
id = arcid
#since the arclist holds the issueids, and the pertinent reading order - we need to strip out the reading order so this works.
aclist = ''
if arclist.startswith('M'):
islist = arclist[1:]
else:
for ac in arclist.split('|'):
aclist += ac[:ac.find(',')] + '|'
if aclist.endswith('|'):
aclist = aclist[:-1]
islist = aclist
else:
id = comicid
islist = None
searched = pulldetails(id, 'issue', None, 0, islist)
if searched is None:
return False
totalResults = searched.getElementsByTagName('number_of_total_results')[0].firstChild.wholeText
logger.fdebug("there are " + str(totalResults) + " search results...")
if not totalResults:
return False
countResults = 0
while (countResults < int(totalResults)):
logger.fdebug("querying range from " + str(countResults) + " to " + str(countResults + 100))
if countResults > 0:
#new api - have to change to page # instead of offset count
offsetcount = countResults
searched = pulldetails(id, 'issue', None, offsetcount, islist)
issuechoice, tmpdate = GetIssuesInfo(id, searched, arcid)
if tmpdate < firstdate:
firstdate = tmpdate
ndic = ndic + issuechoice
#search results are limited to 100 and by pagination now...let's account for this.
countResults = countResults + 100
issue['issuechoice'] = ndic
issue['firstdate'] = firstdate
return issue
elif type == 'comic':
dom = pulldetails(comicid, 'comic', None, 1)
return GetComicInfo(comicid, dom)
elif any([type == 'image', type == 'firstissue']):
dom = pulldetails(comicid, type, issueid, 1)
return Getissue(issueid, dom, type)
elif type == 'storyarc':
dom = pulldetails(arc, 'storyarc', None, 1)
return GetComicInfo(issueid, dom)
elif type == 'comicyears':
#used by the story arc searcher when adding a given arc to poll each ComicID in order to populate the Series Year & volume (hopefully).
#this grabs each issue based on issueid, and then subsets the comicid for each to be used later.
#set the offset to 0, since we're doing a filter.
dom = pulldetails(arcid, 'comicyears', offset=0, comicidlist=comicidlist)
return GetSeriesYears(dom)
elif type == 'import':
#used by the importer when doing a scan with metatagging enabled. If metatagging comes back true, then there's an IssueID present
#within the tagging (with CT). This compiles all of the IssueID's during a scan (in 100's), and returns the corresponding CV data
#related to the given IssueID's - namely ComicID, Name, Volume (more at some point, but those are the important ones).
offset = 1
id_count = 0
import_list = []
logger.fdebug('comicidlist:' + str(comicidlist))
while id_count < len(comicidlist):
#break it up by 100 per api hit
#do the first 100 regardless
in_cnt = 0
if id_count + 100 <= len(comicidlist):
endcnt = id_count + 100
else:
endcnt = len(comicidlist)
for i in range(id_count, endcnt):
if in_cnt == 0:
tmpidlist = str(comicidlist[i])
else:
tmpidlist += '|' + str(comicidlist[i])
in_cnt +=1
logger.fdebug('tmpidlist: ' + str(tmpidlist))
searched = pulldetails(None, 'import', offset=0, comicidlist=tmpidlist)
if searched is None:
break
else:
tGIL = GetImportList(searched)
import_list += tGIL
id_count +=100
return import_list
elif type == 'update_dates':
dom = pulldetails(None, 'update_dates', offset=1, comicidlist=comicidlist)
return UpdateDates(dom)
def GetComicInfo(comicid, dom, safechk=None):
if safechk is None:
#safetycheck when checking comicvine. If it times out, increment the chk on retry attempts up until 5 tries then abort.
safechk = 1
elif safechk > 4:
logger.error('Unable to add / refresh the series due to inablity to retrieve data from ComicVine. You might want to try abit later and/or make sure ComicVine is up.')
return
#comicvine isn't as up-to-date with issue counts..
#so this can get really buggered, really fast.
tracks = dom.getElementsByTagName('issue')
try:
cntit = dom.getElementsByTagName('count_of_issues')[0].firstChild.wholeText
except:
cntit = len(tracks)
trackcnt = len(tracks)
logger.fdebug("number of issues I counted: " + str(trackcnt))
logger.fdebug("number of issues CV says it has: " + str(cntit))
# if the two don't match, use trackcnt as count_of_issues might be not upto-date for some reason
if int(trackcnt) != int(cntit):
cntit = trackcnt
vari = "yes"
else: vari = "no"
logger.fdebug("vari is set to: " + str(vari))
#if str(trackcnt) != str(int(cntit)+2):
# cntit = int(cntit) + 1
comic = {}
comicchoice = []
cntit = int(cntit)
#retrieve the first xml tag (<tag>data</tag>)
#that the parser finds with name tagName:
# to return the parent name of the <name> node : dom.getElementsByTagName('name')[0].parentNode.nodeName
# where [0] denotes the number of the name field(s)
# where nodeName denotes the parentNode : ComicName = results, publisher = publisher, issues = issue
try:
names = len(dom.getElementsByTagName('name'))
n = 0
comic['ComicPublisher'] = 'Unknown' #set this to a default value here so that it will carry through properly
while (n < names):
if dom.getElementsByTagName('name')[n].parentNode.nodeName == 'results':
try:
comic['ComicName'] = dom.getElementsByTagName('name')[n].firstChild.wholeText
comic['ComicName'] = comic['ComicName'].rstrip()
except:
logger.error('There was a problem retrieving the given data from ComicVine. Ensure that www.comicvine.com is accessible AND that you have provided your OWN ComicVine API key.')
return
elif dom.getElementsByTagName('name')[n].parentNode.nodeName == 'publisher':
try:
comic['ComicPublisher'] = dom.getElementsByTagName('name')[n].firstChild.wholeText
except:
comic['ComicPublisher'] = "Unknown"
n += 1
except:
logger.warn('Something went wrong retrieving from ComicVine. Ensure your API is up-to-date and that comicvine is accessible')
return
try:
comic['ComicYear'] = dom.getElementsByTagName('start_year')[0].firstChild.wholeText
except:
comic['ComicYear'] = '0000'
#safety check, cause you known, dufus'...
if any([comic['ComicYear'][-1:] == '-', comic['ComicYear'][-1:] == '?']):
comic['ComicYear'] = comic['ComicYear'][:-1]
try:
comic['ComicURL'] = dom.getElementsByTagName('site_detail_url')[trackcnt].firstChild.wholeText
except:
#this should never be an exception. If it is, it's probably due to CV timing out - so let's sleep for abit then retry.
logger.warn('Unable to retrieve URL for volume. This is usually due to a timeout to CV, or going over the API. Retrying again in 10s.')
time.sleep(10)
safechk +=1
GetComicInfo(comicid, dom, safechk)
desdeck = 0
#the description field actually holds the Volume# - so let's grab it
desc_soup = None
try:
descchunk = dom.getElementsByTagName('description')[0].firstChild.wholeText
desc_soup = Soup(descchunk, "html.parser")
desclinks = desc_soup.findAll('a')
comic_desc = drophtml(descchunk)
desdeck +=1
except:
comic_desc = 'None'
#sometimes the deck has volume labels
try:
deckchunk = dom.getElementsByTagName('deck')[0].firstChild.wholeText
comic_deck = deckchunk
desdeck +=1
except:
comic_deck = 'None'
#comic['ComicDescription'] = comic_desc
try:
comic['Aliases'] = dom.getElementsByTagName('aliases')[0].firstChild.wholeText
comic['Aliases'] = re.sub('\n', '##', comic['Aliases']).strip()
if comic['Aliases'][-2:] == '##':
comic['Aliases'] = comic['Aliases'][:-2]
#logger.fdebug('Aliases: ' + str(aliases))
except:
comic['Aliases'] = 'None'
comic['ComicVersion'] = 'None' #noversion'
#figure out if it's a print / digital edition.
comic['Type'] = 'None'
if comic_deck != 'None':
if any(['print' in comic_deck.lower(), 'digital' in comic_deck.lower(), 'paperback' in comic_deck.lower(), 'one shot' in re.sub('-', '', comic_deck.lower()).strip(), 'hardcover' in comic_deck.lower()]):
if all(['print' in comic_deck.lower(), 'reprint' not in comic_deck.lower()]):
comic['Type'] = 'Print'
elif 'digital' in comic_deck.lower():
comic['Type'] = 'Digital'
elif 'paperback' in comic_deck.lower():
comic['Type'] = 'TPB'
elif 'hardcover' in comic_deck.lower():
comic['Type'] = 'HC'
elif 'oneshot' in re.sub('-', '', comic_deck.lower()).strip():
comic['Type'] = 'One-Shot'
else:
comic['Type'] = 'Print'
if comic_desc != 'None' and comic['Type'] == 'None':
if 'print' in comic_desc[:60].lower() and all(['for the printed edition' not in comic_desc.lower(), 'print edition can be found' not in comic_desc.lower(), 'reprints' not in comic_desc.lower()]):
comic['Type'] = 'Print'
elif 'digital' in comic_desc[:60].lower() and 'digital edition can be found' not in comic_desc.lower():
comic['Type'] = 'Digital'
elif all(['paperback' in comic_desc[:60].lower(), 'paperback can be found' not in comic_desc.lower()]) or 'collects' in comic_desc[:60].lower():
comic['Type'] = 'TPB'
elif 'hardcover' in comic_desc[:60].lower() and 'hardcover can be found' not in comic_desc.lower():
comic['Type'] = 'HC'
elif any(['one-shot' in comic_desc[:60].lower(), 'one shot' in comic_desc[:60].lower()]) and any(['can be found' not in comic_desc.lower(), 'following the' not in comic_desc.lower(), 'after the' not in comic_desc.lower()]):
i = 0
comic['Type'] = 'One-Shot'
avoidwords = ['preceding', 'after the', 'following the']
while i < 2:
if i == 0:
cbd = 'one-shot'
elif i == 1:
cbd = 'one shot'
tmp1 = comic_desc[:60].lower().find(cbd)
if tmp1 != -1:
for x in avoidwords:
tmp2 = comic_desc[:tmp1].lower().find(x)
if tmp2 != -1:
logger.fdebug('FAKE NEWS: caught incorrect reference to one-shot. Forcing to Print')
comic['Type'] = 'Print'
i = 3
break
i+=1
else:
comic['Type'] = 'Print'
if all([comic_desc != 'None', 'trade paperback' in comic_desc[:30].lower(), 'collecting' in comic_desc[:40].lower()]):
#ie. Trade paperback collecting Marvel Team-Up #9-11, 48-51, 72, 110 & 145.
first_collect = comic_desc.lower().find('collecting')
#logger.info('first_collect: %s' % first_collect)
#logger.info('comic_desc: %s' % comic_desc)
#logger.info('desclinks: %s' % desclinks)
issue_list = []
micdrop = []
if desc_soup is not None:
#if it's point form bullets, ignore it cause it's not the current volume stuff.
test_it = desc_soup.find('ul')
if test_it:
for x in test_it.findAll('li'):
if any(['Next' in x.findNext(text=True), 'Previous' in x.findNext(text=True)]):
mic_check = x.find('a')
micdrop.append(mic_check['data-ref-id'])
for fc in desclinks:
try:
fc_id = fc['data-ref-id']
except:
continue
if fc_id in micdrop:
continue
fc_name = fc.findNext(text=True)
if fc_id.startswith('4000'):
fc_cid = None
fc_isid = fc_id
iss_start = fc_name.find('#')
issuerun = fc_name[iss_start:].strip()
fc_name = fc_name[:iss_start].strip()
elif fc_id.startswith('4050'):
fc_cid = fc_id
fc_isid = None
issuerun = fc.next_sibling
if issuerun is not None:
lines = re.sub("[^0-9]", ' ', issuerun).strip().split(' ')
if len(lines) > 0:
for x in sorted(lines, reverse=True):
srchline = issuerun.rfind(x)
if srchline != -1:
try:
if issuerun[srchline+len(x)] == ',' or issuerun[srchline+len(x)] == '.' or issuerun[srchline+len(x)] == ' ':
issuerun = issuerun[:srchline+len(x)]
break
except Exception as e:
#logger.warn('[ERROR] %s' % e)
continue
else:
iss_start = fc_name.find('#')
issuerun = fc_name[iss_start:].strip()
fc_name = fc_name[:iss_start].strip()
if issuerun.strip().endswith('.') or issuerun.strip().endswith(','):
#logger.fdebug('Changed issuerun from %s to %s' % (issuerun, issuerun[:-1]))
issuerun = issuerun.strip()[:-1]
if issuerun.endswith(' and '):
issuerun = issuerun[:-4].strip()
elif issuerun.endswith(' and'):
issuerun = issuerun[:-3].strip()
else:
continue
# except:
# pass
issue_list.append({'series': fc_name,
'comicid': fc_cid,
'issueid': fc_isid,
'issues': issuerun})
#first_collect = cis
logger.info('Collected issues in volume: %s' % issue_list)
if len(issue_list) == 0:
comic['Issue_List'] = 'None'
else:
comic['Issue_List'] = issue_list
else:
comic['Issue_List'] = 'None'
while (desdeck > 0):
if desdeck == 1:
if comic_desc == 'None':
comicDes = comic_deck[:30]
else:
#extract the first 60 characters
comicDes = comic_desc[:60].replace('New 52', '')
elif desdeck == 2:
#extract the characters from the deck
comicDes = comic_deck[:30].replace('New 52', '')
else:
break
i = 0
while (i < 2):
if 'volume' in comicDes.lower():
#found volume - let's grab it.
v_find = comicDes.lower().find('volume')
#arbitrarily grab the next 10 chars (6 for volume + 1 for space + 3 for the actual vol #)
#increased to 10 to allow for text numbering (+5 max)
#sometimes it's volume 5 and ocassionally it's fifth volume.
if comicDes[v_find+7:comicDes.find(' ', v_find+7)].isdigit():
comic['ComicVersion'] = re.sub("[^0-9]", "", comicDes[v_find+7:comicDes.find(' ', v_find+7)]).strip()
break
elif i == 0:
vfind = comicDes[v_find:v_find +15] #if it's volume 5 format
basenums = {'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', 'ten': '10', 'i': '1', 'ii': '2', 'iii': '3', 'iv': '4', 'v': '5'}
logger.fdebug('volume X format - ' + str(i) + ': ' + vfind)
else:
vfind = comicDes[:v_find] # if it's fifth volume format
basenums = {'zero': '0', 'first': '1', 'second': '2', 'third': '3', 'fourth': '4', 'fifth': '5', 'sixth': '6', 'seventh': '7', 'eighth': '8', 'nineth': '9', 'tenth': '10', 'i': '1', 'ii': '2', 'iii': '3', 'iv': '4', 'v': '5'}
logger.fdebug('X volume format - ' + str(i) + ': ' + vfind)
volconv = ''
for nums in basenums:
if nums in vfind.lower():
sconv = basenums[nums]
vfind = re.sub(nums, sconv, vfind.lower())
break
#logger.info('volconv: ' + str(volconv))
#now we attempt to find the character position after the word 'volume'
if i == 0:
volthis = vfind.lower().find('volume')
volthis = volthis + 6 # add on the actual word to the position so that we can grab the subsequent digit
vfind = vfind[volthis:volthis + 4] # grab the next 4 characters ;)
elif i == 1:
volthis = vfind.lower().find('volume')
vfind = vfind[volthis - 4:volthis] # grab the next 4 characters ;)
if '(' in vfind:
#bracket detected in versioning'
vfindit = re.findall('[^()]+', vfind)
vfind = vfindit[0]
vf = re.findall('[^<>]+', vfind)
try:
ledigit = re.sub("[^0-9]", "", vf[0])
if ledigit != '':
comic['ComicVersion'] = ledigit
logger.fdebug("Volume information found! Adding to series record : volume " + comic['ComicVersion'])
break
except:
pass
i += 1
else:
i += 1
if comic['ComicVersion'] == 'None':
logger.fdebug('comic[ComicVersion]:' + str(comic['ComicVersion']))
desdeck -= 1
else:
break
if vari == "yes":
comic['ComicIssues'] = str(cntit)
else:
comic['ComicIssues'] = dom.getElementsByTagName('count_of_issues')[0].firstChild.wholeText
comic['ComicImage'] = dom.getElementsByTagName('super_url')[0].firstChild.wholeText
comic['ComicImageALT'] = dom.getElementsByTagName('small_url')[0].firstChild.wholeText
comic['FirstIssueID'] = dom.getElementsByTagName('id')[0].firstChild.wholeText
#logger.info('comic: %s' % comic)
return comic
def GetIssuesInfo(comicid, dom, arcid=None):
subtracks = dom.getElementsByTagName('issue')
if not mylar.CONFIG.CV_ONLY:
cntiss = dom.getElementsByTagName('count_of_issues')[0].firstChild.wholeText
logger.fdebug("issues I've counted: " + str(len(subtracks)))
logger.fdebug("issues CV says it has: " + str(int(cntiss)))
if int(len(subtracks)) != int(cntiss):
logger.fdebug("CV's count is wrong, I counted different...going with my count for physicals" + str(len(subtracks)))
cntiss = len(subtracks) # assume count of issues is wrong, go with ACTUAL physical api count
cntiss = int(cntiss)
n = cntiss -1
else:
n = int(len(subtracks))
tempissue = {}
issuech = []
firstdate = '2099-00-00'
for subtrack in subtracks:
if not mylar.CONFIG.CV_ONLY:
if (dom.getElementsByTagName('name')[n].firstChild) is not None:
issue['Issue_Name'] = dom.getElementsByTagName('name')[n].firstChild.wholeText
else:
issue['Issue_Name'] = 'None'
issue['Issue_ID'] = dom.getElementsByTagName('id')[n].firstChild.wholeText
issue['Issue_Number'] = dom.getElementsByTagName('issue_number')[n].firstChild.wholeText
issuech.append({
'Issue_ID': issue['Issue_ID'],
'Issue_Number': issue['Issue_Number'],
'Issue_Name': issue['Issue_Name']
})
else:
try:
totnames = len(subtrack.getElementsByTagName('name'))
tot = 0
while (tot < totnames):
if subtrack.getElementsByTagName('name')[tot].parentNode.nodeName == 'volume':
tempissue['ComicName'] = subtrack.getElementsByTagName('name')[tot].firstChild.wholeText
elif subtrack.getElementsByTagName('name')[tot].parentNode.nodeName == 'issue':
try:
tempissue['Issue_Name'] = subtrack.getElementsByTagName('name')[tot].firstChild.wholeText
except:
tempissue['Issue_Name'] = None
tot += 1
except:
tempissue['ComicName'] = 'None'
try:
totids = len(subtrack.getElementsByTagName('id'))
idt = 0
while (idt < totids):
if subtrack.getElementsByTagName('id')[idt].parentNode.nodeName == 'volume':
tempissue['Comic_ID'] = subtrack.getElementsByTagName('id')[idt].firstChild.wholeText
elif subtrack.getElementsByTagName('id')[idt].parentNode.nodeName == 'issue':
tempissue['Issue_ID'] = subtrack.getElementsByTagName('id')[idt].firstChild.wholeText
idt += 1
except:
tempissue['Issue_Name'] = 'None'
try:
tempissue['CoverDate'] = subtrack.getElementsByTagName('cover_date')[0].firstChild.wholeText
except:
tempissue['CoverDate'] = '0000-00-00'
try:
tempissue['StoreDate'] = subtrack.getElementsByTagName('store_date')[0].firstChild.wholeText
except:
tempissue['StoreDate'] = '0000-00-00'
try:
digital_desc = subtrack.getElementsByTagName('description')[0].firstChild.wholeText
except:
tempissue['DigitalDate'] = '0000-00-00'
else:
tempissue['DigitalDate'] = '0000-00-00'
if all(['digital' in digital_desc.lower()[-90:], 'print' in digital_desc.lower()[-90:]]):
#get the digital date of issue here...
mff = mylar.filechecker.FileChecker()
vlddate = mff.checkthedate(digital_desc[-90:], fulldate=True)
#logger.fdebug('vlddate: %s' % vlddate)
if vlddate:
tempissue['DigitalDate'] = vlddate
try:
tempissue['Issue_Number'] = subtrack.getElementsByTagName('issue_number')[0].firstChild.wholeText
except:
logger.fdebug('No Issue Number available - Trade Paperbacks, Graphic Novels and Compendiums are not supported as of yet.')
try:
tempissue['ComicImage'] = subtrack.getElementsByTagName('small_url')[0].firstChild.wholeText
except:
tempissue['ComicImage'] = 'None'
try:
tempissue['ComicImageALT'] = subtrack.getElementsByTagName('medium_url')[0].firstChild.wholeText
except:
tempissue['ComicImageALT'] = 'None'
if arcid is None:
issuech.append({
'Comic_ID': comicid,
'Issue_ID': tempissue['Issue_ID'],
'Issue_Number': tempissue['Issue_Number'],
'Issue_Date': tempissue['CoverDate'],
'Store_Date': tempissue['StoreDate'],
'Digital_Date': tempissue['DigitalDate'],
'Issue_Name': tempissue['Issue_Name'],
'Image': tempissue['ComicImage'],
'ImageALT': tempissue['ComicImageALT']
})
else:
issuech.append({
'ArcID': arcid,
'ComicName': tempissue['ComicName'],
'ComicID': tempissue['Comic_ID'],
'IssueID': tempissue['Issue_ID'],
'Issue_Number': tempissue['Issue_Number'],
'Issue_Date': tempissue['CoverDate'],
'Store_Date': tempissue['StoreDate'],
'Digital_Date': tempissue['DigitalDate'],
'Issue_Name': tempissue['Issue_Name']
})
if tempissue['CoverDate'] < firstdate and tempissue['CoverDate'] != '0000-00-00':
firstdate = tempissue['CoverDate']
n-= 1
#logger.fdebug('issue_info: %s' % issuech)
#issue['firstdate'] = firstdate
return issuech, firstdate
def Getissue(issueid, dom, type):
#if the Series Year doesn't exist, get the first issue and take the date from that
if type == 'firstissue':
try:
first_year = dom.getElementsByTagName('cover_date')[0].firstChild.wholeText
except:
first_year = '0000'
return first_year
the_year = first_year[:4]
the_month = first_year[5:7]
the_date = the_year + '-' + the_month
return the_year
else:
try:
image = dom.getElementsByTagName('super_url')[0].firstChild.wholeText
except:
image = None
try:
image_alt = dom.getElementsByTagName('small_url')[0].firstChild.wholeText
except:
image_alt = None
return {'image': image,
'image_alt': image_alt}
def GetSeriesYears(dom):
#used by the 'add a story arc' option to individually populate the Series Year for each series within the given arc.
#series year is required for alot of functionality.
series = dom.getElementsByTagName('volume')
tempseries = {}
serieslist = []
for dm in series:
try:
totids = len(dm.getElementsByTagName('id'))
idc = 0
while (idc < totids):
if dm.getElementsByTagName('id')[idc].parentNode.nodeName == 'volume':
tempseries['ComicID'] = dm.getElementsByTagName('id')[idc].firstChild.wholeText
idc+=1
except:
logger.warn('There was a problem retrieving a comicid for a series within the arc. This will have to manually corrected most likely.')
tempseries['ComicID'] = 'None'
tempseries['Series'] = 'None'
tempseries['Publisher'] = 'None'
try:
totnames = len(dm.getElementsByTagName('name'))
namesc = 0
while (namesc < totnames):
if dm.getElementsByTagName('name')[namesc].parentNode.nodeName == 'volume':
tempseries['Series'] = dm.getElementsByTagName('name')[namesc].firstChild.wholeText
elif dm.getElementsByTagName('name')[namesc].parentNode.nodeName == 'publisher':
tempseries['Publisher'] = dm.getElementsByTagName('name')[namesc].firstChild.wholeText
namesc+=1
except:
logger.warn('There was a problem retrieving a Series Name or Publisher for a series within the arc. This will have to manually corrected.')
try:
tempseries['SeriesYear'] = dm.getElementsByTagName('start_year')[0].firstChild.wholeText
except:
logger.warn('There was a problem retrieving the start year for a particular series within the story arc.')
tempseries['SeriesYear'] = '0000'
#cause you know, dufus'...
if tempseries['SeriesYear'][-1:] == '-':
tempseries['SeriesYear'] = tempseries['SeriesYear'][:-1]
desdeck = 0
#the description field actually holds the Volume# - so let's grab it
desc_soup = None
try:
descchunk = dm.getElementsByTagName('description')[0].firstChild.wholeText
desc_soup = Soup(descchunk, "html.parser")
desclinks = desc_soup.findAll('a')
comic_desc = drophtml(descchunk)
desdeck +=1
except:
comic_desc = 'None'
#sometimes the deck has volume labels
try:
deckchunk = dm.getElementsByTagName('deck')[0].firstChild.wholeText
comic_deck = deckchunk
desdeck +=1
except:
comic_deck = 'None'
#comic['ComicDescription'] = comic_desc
try:
tempseries['Aliases'] = dm.getElementsByTagName('aliases')[0].firstChild.wholeText
tempseries['Aliases'] = re.sub('\n', '##', tempseries['Aliases']).strip()
if tempseries['Aliases'][-2:] == '##':
tempseries['Aliases'] = tempseries['Aliases'][:-2]
#logger.fdebug('Aliases: ' + str(aliases))
except:
tempseries['Aliases'] = 'None'
tempseries['Volume'] = 'None' #noversion'
#figure out if it's a print / digital edition.
tempseries['Type'] = 'None'
if comic_deck != 'None':
if any(['print' in comic_deck.lower(), 'digital' in comic_deck.lower(), 'paperback' in comic_deck.lower(), 'one shot' in re.sub('-', '', comic_deck.lower()).strip(), 'hardcover' in comic_deck.lower()]):
if 'print' in comic_deck.lower():
tempseries['Type'] = 'Print'
elif 'digital' in comic_deck.lower():
tempseries['Type'] = 'Digital'
elif 'paperback' in comic_deck.lower():
tempseries['Type'] = 'TPB'
elif 'hardcover' in comic_deck.lower():
tempseries['Type'] = 'HC'
elif 'oneshot' in re.sub('-', '', comic_deck.lower()).strip():
tempseries['Type'] = 'One-Shot'
if comic_desc != 'None' and tempseries['Type'] == 'None':
if 'print' in comic_desc[:60].lower() and 'print edition can be found' not in comic_desc.lower():
tempseries['Type'] = 'Print'
elif 'digital' in comic_desc[:60].lower() and 'digital edition can be found' not in comic_desc.lower():
tempseries['Type'] = 'Digital'
elif all(['paperback' in comic_desc[:60].lower(), 'paperback can be found' not in comic_desc.lower()]) or 'collects' in comic_desc[:60].lower():
tempseries['Type'] = 'TPB'
elif 'hardcover' in comic_desc[:60].lower() and 'hardcover can be found' not in comic_desc.lower():
tempseries['Type'] = 'HC'
elif any(['one-shot' in comic_desc[:60].lower(), 'one shot' in comic_desc[:60].lower()]) and any(['can be found' not in comic_desc.lower(), 'following the' not in comic_desc.lower()]):
i = 0
tempseries['Type'] = 'One-Shot'
avoidwords = ['preceding', 'after the special', 'following the']
while i < 2:
if i == 0:
cbd = 'one-shot'
elif i == 1:
cbd = 'one shot'
tmp1 = comic_desc[:60].lower().find(cbd)
if tmp1 != -1:
for x in avoidwords:
tmp2 = comic_desc[:tmp1].lower().find(x)
if tmp2 != -1:
logger.fdebug('FAKE NEWS: caught incorrect reference to one-shot. Forcing to Print')
tempseries['Type'] = 'Print'
i = 3
break
i+=1
else:
tempseries['Type'] = 'Print'
if all([comic_desc != 'None', 'trade paperback' in comic_desc[:30].lower(), 'collecting' in comic_desc[:40].lower()]):
#ie. Trade paperback collecting Marvel Team-Up #9-11, 48-51, 72, 110 & 145.
first_collect = comic_desc.lower().find('collecting')
#logger.info('first_collect: %s' % first_collect)
#logger.info('comic_desc: %s' % comic_desc)
#logger.info('desclinks: %s' % desclinks)
issue_list = []
micdrop = []
if desc_soup is not None:
#if it's point form bullets, ignore it cause it's not the current volume stuff.
test_it = desc_soup.find('ul')
if test_it:
for x in test_it.findAll('li'):
if any(['Next' in x.findNext(text=True), 'Previous' in x.findNext(text=True)]):
mic_check = x.find('a')
micdrop.append(mic_check['data-ref-id'])
for fc in desclinks:
#logger.info('fc: %s' % fc)
fc_id = fc['data-ref-id']
#logger.info('fc_id: %s' % fc_id)
if fc_id in micdrop:
continue
fc_name = fc.findNext(text=True)
if fc_id.startswith('4000'):
fc_cid = None
fc_isid = fc_id
iss_start = fc_name.find('#')
issuerun = fc_name[iss_start:].strip()
fc_name = fc_name[:iss_start].strip()
elif fc_id.startswith('4050'):
fc_cid = fc_id
fc_isid = None
issuerun = fc.next_sibling
if issuerun is not None:
lines = re.sub("[^0-9]", ' ', issuerun).strip().split(' ')
if len(lines) > 0:
for x in sorted(lines, reverse=True):
srchline = issuerun.rfind(x)
if srchline != -1:
try:
if issuerun[srchline+len(x)] == ',' or issuerun[srchline+len(x)] == '.' or issuerun[srchline+len(x)] == ' ':
issuerun = issuerun[:srchline+len(x)]
break
except Exception as e:
logger.warn('[ERROR] %s' % e)
continue
else:
iss_start = fc_name.find('#')
issuerun = fc_name[iss_start:].strip()
fc_name = fc_name[:iss_start].strip()
if issuerun.endswith('.') or issuerun.endswith(','):
#logger.fdebug('Changed issuerun from %s to %s' % (issuerun, issuerun[:-1]))
issuerun = issuerun[:-1]
if issuerun.endswith(' and '):
issuerun = issuerun[:-4].strip()
elif issuerun.endswith(' and'):
issuerun = issuerun[:-3].strip()
else:
continue
# except:
# pass
issue_list.append({'series': fc_name,
'comicid': fc_cid,
'issueid': fc_isid,
'issues': issuerun})
#first_collect = cis
logger.info('Collected issues in volume: %s' % issue_list)
tempseries['Issue_List'] = issue_list
else:
tempseries['Issue_List'] = 'None'
while (desdeck > 0):
if desdeck == 1:
if comic_desc == 'None':
comicDes = comic_deck[:30]
else:
#extract the first 60 characters
comicDes = comic_desc[:60].replace('New 52', '')
elif desdeck == 2:
#extract the characters from the deck
comicDes = comic_deck[:30].replace('New 52', '')
else:
break
i = 0
while (i < 2):
if 'volume' in comicDes.lower():
#found volume - let's grab it.
v_find = comicDes.lower().find('volume')
#arbitrarily grab the next 10 chars (6 for volume + 1 for space + 3 for the actual vol #)
#increased to 10 to allow for text numbering (+5 max)
#sometimes it's volume 5 and ocassionally it's fifth volume.
if i == 0:
vfind = comicDes[v_find:v_find +15] #if it's volume 5 format
basenums = {'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9', 'ten': '10', 'i': '1', 'ii': '2', 'iii': '3', 'iv': '4', 'v': '5'}
logger.fdebug('volume X format - %s: %s' % (i, vfind))
else:
vfind = comicDes[:v_find] # if it's fifth volume format
basenums = {'zero': '0', 'first': '1', 'second': '2', 'third': '3', 'fourth': '4', 'fifth': '5', 'sixth': '6', 'seventh': '7', 'eighth': '8', 'nineth': '9', 'tenth': '10', 'i': '1', 'ii': '2', 'iii': '3', 'iv': '4', 'v': '5'}
logger.fdebug('X volume format - %s: %s' % (i, vfind))
volconv = ''
for nums in basenums:
if nums in vfind.lower():
sconv = basenums[nums]
vfind = re.sub(nums, sconv, vfind.lower())
break
#logger.info('volconv: ' + str(volconv))
#now we attempt to find the character position after the word 'volume'
if i == 0:
volthis = vfind.lower().find('volume')
volthis = volthis + 6 # add on the actual word to the position so that we can grab the subsequent digit
vfind = vfind[volthis:volthis + 4] # grab the next 4 characters ;)
elif i == 1:
volthis = vfind.lower().find('volume')
vfind = vfind[volthis - 4:volthis] # grab the next 4 characters ;)
if '(' in vfind:
#bracket detected in versioning'
vfindit = re.findall('[^()]+', vfind)
vfind = vfindit[0]
vf = re.findall('[^<>]+', vfind)
try:
ledigit = re.sub("[^0-9]", "", vf[0])
if ledigit != '':
tempseries['Volume'] = ledigit
logger.fdebug("Volume information found! Adding to series record : volume %s" % tempseries['Volume'])
break
except:
pass
i += 1
else:
i += 1
if tempseries['Volume'] == 'None':
logger.fdebug('tempseries[Volume]: %s' % tempseries['Volume'])
desdeck -= 1
else:
break
serieslist.append({"ComicID": tempseries['ComicID'],
"ComicName": tempseries['Series'],
"SeriesYear": tempseries['SeriesYear'],
"Publisher": tempseries['Publisher'],
"Volume": tempseries['Volume'],
"Aliases": tempseries['Aliases'],
"Type": tempseries['Type']})
return serieslist
def UpdateDates(dom):
issues = dom.getElementsByTagName('issue')
tempissue = {}
issuelist = []
for dm in issues:
tempissue['ComicID'] = 'None'
tempissue['IssueID'] = 'None'
try:
totids = len(dm.getElementsByTagName('id'))
idc = 0
while (idc < totids):
if dm.getElementsByTagName('id')[idc].parentNode.nodeName == 'volume':
tempissue['ComicID'] = dm.getElementsByTagName('id')[idc].firstChild.wholeText
if dm.getElementsByTagName('id')[idc].parentNode.nodeName == 'issue':
tempissue['IssueID'] = dm.getElementsByTagName('id')[idc].firstChild.wholeText
idc+=1
except:
logger.warn('There was a problem retrieving a comicid/issueid for the given issue. This will have to manually corrected most likely.')
tempissue['SeriesTitle'] = 'None'
tempissue['IssueTitle'] = 'None'
try:
totnames = len(dm.getElementsByTagName('name'))
namesc = 0
while (namesc < totnames):
if dm.getElementsByTagName('name')[namesc].parentNode.nodeName == 'issue':
tempissue['IssueTitle'] = dm.getElementsByTagName('name')[namesc].firstChild.wholeText
elif dm.getElementsByTagName('name')[namesc].parentNode.nodeName == 'volume':
tempissue['SeriesTitle'] = dm.getElementsByTagName('name')[namesc].firstChild.wholeText
namesc+=1
except:
logger.warn('There was a problem retrieving the Series Title / Issue Title for a series within the arc. This will have to manually corrected.')
try:
tempissue['CoverDate'] = dm.getElementsByTagName('cover_date')[0].firstChild.wholeText
except:
tempissue['CoverDate'] = '0000-00-00'
try:
tempissue['StoreDate'] = dm.getElementsByTagName('store_date')[0].firstChild.wholeText
except:
tempissue['StoreDate'] = '0000-00-00'
try:
tempissue['IssueNumber'] = dm.getElementsByTagName('issue_number')[0].firstChild.wholeText
except:
logger.fdebug('No Issue Number available - Trade Paperbacks, Graphic Novels and Compendiums are not supported as of yet.')
tempissue['IssueNumber'] = 'None'
try:
tempissue['date_last_updated'] = dm.getElementsByTagName('date_last_updated')[0].firstChild.wholeText
except:
tempissue['date_last_updated'] = '0000-00-00'
issuelist.append({'ComicID': tempissue['ComicID'],
'IssueID': tempissue['IssueID'],
'SeriesTitle': tempissue['SeriesTitle'],
'IssueTitle': tempissue['IssueTitle'],
'CoverDate': tempissue['CoverDate'],
'StoreDate': tempissue['StoreDate'],
'IssueNumber': tempissue['IssueNumber'],
'Date_Last_Updated': tempissue['date_last_updated']})
return issuelist
def GetImportList(results):
importlist = results.getElementsByTagName('issue')
serieslist = []
importids = {}
tempseries = {}
for implist in importlist:
try:
totids = len(implist.getElementsByTagName('id'))
idt = 0
while (idt < totids):
if implist.getElementsByTagName('id')[idt].parentNode.nodeName == 'volume':
tempseries['ComicID'] = implist.getElementsByTagName('id')[idt].firstChild.wholeText
elif implist.getElementsByTagName('id')[idt].parentNode.nodeName == 'issue':
tempseries['IssueID'] = implist.getElementsByTagName('id')[idt].firstChild.wholeText
idt += 1
except:
tempseries['ComicID'] = None
try:
totnames = len(implist.getElementsByTagName('name'))
tot = 0
while (tot < totnames):
if implist.getElementsByTagName('name')[tot].parentNode.nodeName == 'volume':
tempseries['ComicName'] = implist.getElementsByTagName('name')[tot].firstChild.wholeText
elif implist.getElementsByTagName('name')[tot].parentNode.nodeName == 'issue':
try:
tempseries['Issue_Name'] = implist.getElementsByTagName('name')[tot].firstChild.wholeText
except:
tempseries['Issue_Name'] = None
tot += 1
except:
tempseries['ComicName'] = 'None'
try:
tempseries['Issue_Number'] = implist.getElementsByTagName('issue_number')[0].firstChild.wholeText
except:
logger.fdebug('No Issue Number available - Trade Paperbacks, Graphic Novels and Compendiums are not supported as of yet.')
logger.info('tempseries:' + str(tempseries))
serieslist.append({"ComicID": tempseries['ComicID'],
"IssueID": tempseries['IssueID'],
"ComicName": tempseries['ComicName'],
"Issue_Name": tempseries['Issue_Name'],
"Issue_Number": tempseries['Issue_Number']})
return serieslist
def drophtml(html):
soup = Soup(html, "html.parser")
text_parts = soup.findAll(text=True)
#print ''.join(text_parts)
return ''.join(text_parts)
| 52,004 | Python | .py | 986 | 38.459432 | 249 | 0.536743 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,261 | webserve.py | evilhero_mylar/mylar/webserve.py | # This file is part of Mylar.
# -*- coding: utf-8 -*-
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import os
import io
import sys
import cherrypy
import requests
import datetime
from datetime import timedelta, date
import re
import json
import copy
import ntpath
from mako.template import Template
from mako.lookup import TemplateLookup
from mako import exceptions
import time
import threading
import csv
import platform
import urllib
import shutil
import mylar
from mylar import logger, db, importer, mb, search, filechecker, helpers, updater, parseit, weeklypull, PostProcessor, librarysync, moveit, Failed, readinglist, notifiers, sabparse, config
from mylar.auth import AuthController, require
import simplejson as simplejson
from operator import itemgetter
def serve_template(templatename, **kwargs):
interface_dir = os.path.join(str(mylar.PROG_DIR), 'data/interfaces/')
template_dir = os.path.join(str(interface_dir), mylar.CONFIG.INTERFACE)
_hplookup = TemplateLookup(directories=[template_dir])
try:
template = _hplookup.get_template(templatename)
return template.render(http_root=mylar.CONFIG.HTTP_ROOT, **kwargs)
except:
return exceptions.html_error_template().render()
class WebInterface(object):
auth = AuthController()
def index(self):
if mylar.SAFESTART:
raise cherrypy.HTTPRedirect("manageComics")
else:
raise cherrypy.HTTPRedirect("home")
index.exposed=True
def home(self):
comics = helpers.havetotals()
return serve_template(templatename="index.html", title="Home", comics=comics, alphaindex=mylar.CONFIG.ALPHAINDEX)
home.exposed = True
def comicDetails(self, ComicID):
myDB = db.DBConnection()
comic = myDB.selectone('SELECT * FROM comics WHERE ComicID=?', [ComicID]).fetchone()
if comic is None:
raise cherrypy.HTTPRedirect("home")
totalissues = comic['Total']
haveissues = comic['Have']
if not haveissues:
haveissues = 0
try:
percent = (haveissues *100.0) /totalissues
if percent > 100:
percent = 101
except (ZeroDivisionError, TypeError):
percent = 0
totalissues = '?'
#let's cheat. :)
#comicskip = myDB.select('SELECT * from comics order by ComicSortName COLLATE NOCASE')
skipno = len(mylar.COMICSORT['SortOrder'])
lastno = mylar.COMICSORT['LastOrderNo']
lastid = mylar.COMICSORT['LastOrderID']
series = {}
if skipno == 0:
#it's a blank db, let's just null the values and go.
series['Current'] = None
series['Previous'] = None
series['Next'] = None
i = 0
while (i < skipno):
cskip = mylar.COMICSORT['SortOrder'][i]
if cskip['ComicID'] == ComicID:
cursortnum = cskip['ComicOrder']
series['Current'] = cskip['ComicID']
if cursortnum == 0:
# if first record, set the Previous record to the LAST record.
previous = lastid
else:
previous = mylar.COMICSORT['SortOrder'][i -1]['ComicID']
# if last record, set the Next record to the FIRST record.
if cursortnum == lastno:
next = mylar.COMICSORT['SortOrder'][0]['ComicID']
else:
next = mylar.COMICSORT['SortOrder'][i +1]['ComicID']
series['Previous'] = previous
series['Next'] = next
break
i+=1
issues = myDB.select('SELECT * FROM issues WHERE ComicID=? order by Int_IssueNumber DESC', [ComicID])
isCounts = {}
isCounts[1] = 0 #1 skipped
isCounts[2] = 0 #2 wanted
isCounts[3] = 0 #3 archived
isCounts[4] = 0 #4 downloaded
isCounts[5] = 0 #5 ignored
isCounts[6] = 0 #6 failed
isCounts[7] = 0 #7 snatched
#isCounts[8] = 0 #8 read
for curResult in issues:
baseissues = {'skipped': 1, 'wanted': 2, 'archived': 3, 'downloaded': 4, 'ignored': 5, 'failed': 6, 'snatched': 7}
for seas in baseissues:
if curResult['Status'] is None:
continue
else:
if seas in curResult['Status'].lower():
sconv = baseissues[seas]
isCounts[sconv]+=1
continue
isCounts = {
"Skipped": str(isCounts[1]),
"Wanted": str(isCounts[2]),
"Archived": str(isCounts[3]),
"Downloaded": str(isCounts[4]),
"Ignored": str(isCounts[5]),
"Failed": str(isCounts[6]),
"Snatched": str(isCounts[7])
}
usethefuzzy = comic['UseFuzzy']
allowpacks = comic['AllowPacks']
skipped2wanted = "0"
if usethefuzzy is None:
usethefuzzy = "0"
force_continuing = comic['ForceContinuing']
if force_continuing is None:
force_continuing = 0
if mylar.CONFIG.DELETE_REMOVE_DIR is None:
mylar.CONFIG.DELETE_REMOVE_DIR = 0
if allowpacks is None:
allowpacks = "0"
if all([comic['Corrected_SeriesYear'] is not None, comic['Corrected_SeriesYear'] != '', comic['Corrected_SeriesYear'] != 'None']):
if comic['Corrected_SeriesYear'] != comic['ComicYear']:
comic['ComicYear'] = comic['Corrected_SeriesYear']
# imagetopull = myDB.selectone('SELECT issueid from issues where ComicID=? AND Int_IssueNumber=?', [comic['ComicID'], helpers.issuedigits(comic['LatestIssue'])]).fetchone()
# imageurl = mylar.cv.getComic(comic['ComicID'], 'image', issueid=imagetopull[0])
# helpers.getImage(comic['ComicID'], imageurl)
if comic['ComicImage'] is None:
comicImage = 'cache/' + str(ComicID) + '.jpg'
else:
comicImage = comic['ComicImage']
comicpublisher = helpers.publisherImages(comic['ComicPublisher'])
if comic['Collects'] is not None:
issues_list = json.loads(comic['Collects'])
else:
issues_list = None
#logger.info('issues_list: %s' % issues_list)
if comic['Corrected_Type'] == 'TPB':
force_type = 1
elif comic['Corrected_Type'] == 'Print':
force_type = 2
else:
force_type = 0
comicConfig = {
"fuzzy_year0": helpers.radio(int(usethefuzzy), 0),
"fuzzy_year1": helpers.radio(int(usethefuzzy), 1),
"fuzzy_year2": helpers.radio(int(usethefuzzy), 2),
"skipped2wanted": helpers.checked(skipped2wanted),
"force_continuing": helpers.checked(force_continuing),
"force_type": helpers.checked(force_type),
"delete_dir": helpers.checked(mylar.CONFIG.DELETE_REMOVE_DIR),
"allow_packs": helpers.checked(int(allowpacks)),
"corrected_seriesyear": comic['ComicYear'],
"torrentid_32p": comic['TorrentID_32P'],
"totalissues": totalissues,
"haveissues": haveissues,
"percent": percent,
"publisher_image": comicpublisher['publisher_image'],
"publisher_image_alt": comicpublisher['publisher_image_alt'],
"publisher_imageH": comicpublisher['publisher_imageH'],
"publisher_imageW": comicpublisher['publisher_imageW'],
"issue_list": issues_list,
"ComicImage": comicImage + '?' + datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')
}
if mylar.CONFIG.ANNUALS_ON:
annuals = myDB.select("SELECT * FROM annuals WHERE ComicID=? ORDER BY ComicID, Int_IssueNumber DESC", [ComicID])
#we need to load in the annual['ReleaseComicName'] and annual['ReleaseComicID']
#then group by ReleaseComicID, in an attempt to create seperate tables for each different annual series.
#this should allow for annuals, specials, one-shots, etc all to be included if desired.
acnt = 0
aName = []
annuals_list = []
annualinfo = {}
prevcomicid = None
for ann in annuals:
if not any(d.get('annualComicID', None) == str(ann['ReleaseComicID']) for d in aName):
aName.append({"annualComicName": ann['ReleaseComicName'],
"annualComicID": ann['ReleaseComicID']})
issuename = ann['IssueName']
if ann['IssueName'] is not None:
if len(ann['IssueName']) > 75:
issuename = '%s...' % ann['IssueName'][:75]
annuals_list.append({"Issue_Number": ann['Issue_Number'],
"Int_IssueNumber": ann['Int_IssueNumber'],
"IssueName": issuename,
"IssueDate": ann['IssueDate'],
"DigitalDate": ann['DigitalDate'],
"Status": ann['Status'],
"Location": ann['Location'],
"ComicID": ann['ComicID'],
"IssueID": ann['IssueID'],
"ReleaseComicID": ann['ReleaseComicID'],
"ComicName": ann['ComicName'],
"ComicSize": ann['ComicSize'],
"ReleaseComicName": ann['ReleaseComicName'],
"PrevComicID": prevcomicid})
prevcomicid = ann['ReleaseComicID']
acnt+=1
annualinfo = aName
#annualinfo['count'] = acnt
else:
annuals_list = None
aName = None
return serve_template(templatename="comicdetails.html", title=comic['ComicName'], comic=comic, issues=issues, comicConfig=comicConfig, isCounts=isCounts, series=series, annuals=annuals_list, annualinfo=aName)
comicDetails.exposed = True
def searchit(self, name, issue=None, mode=None, type=None, serinfo=None):
if type is None: type = 'comic' # let's default this to comic search only for the time being (will add story arc, characters, etc later)
else: logger.fdebug(str(type) + " mode enabled.")
#mode dictates type of search:
# --series ... search for comicname displaying all results
# --pullseries ... search for comicname displaying a limited # of results based on issue
# --want ... individual comics
if mode is None: mode = 'series'
if len(name) == 0:
raise cherrypy.HTTPRedirect("home")
if type == 'comic' and mode == 'pullseries':
if issue == 0:
#if it's an issue 0, CV doesn't have any data populated yet - so bump it up one to at least get the current results.
issue = 1
try:
searchresults = mb.findComic(name, mode, issue=issue)
except TypeError:
logger.error('Unable to perform required pull-list search for : [name: ' + name + '][issue: ' + issue + '][mode: ' + mode + ']')
return
elif type == 'comic' and mode == 'series':
if name.startswith('4050-'):
mismatch = "no"
comicid = re.sub('4050-', '', name)
logger.info('Attempting to add directly by ComicVineID: ' + str(comicid) + '. I sure hope you know what you are doing.')
threading.Thread(target=importer.addComictoDB, args=[comicid, mismatch, None]).start()
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % comicid)
try:
searchresults = mb.findComic(name, mode, issue=None)
except TypeError:
logger.error('Unable to perform required search for : [name: ' + name + '][mode: ' + mode + ']')
return
elif type == 'comic' and mode == 'want':
try:
searchresults = mb.findComic(name, mode, issue)
except TypeError:
logger.error('Unable to perform required one-off pull-list search for : [name: ' + name + '][issue: ' + issue + '][mode: ' + mode + ']')
return
elif type == 'story_arc':
try:
searchresults = mb.findComic(name, mode=None, issue=None, type='story_arc')
except TypeError:
logger.error('Unable to perform required story-arc search for : [arc: ' + name + '][mode: ' + mode + ']')
return
try:
searchresults = sorted(searchresults, key=itemgetter('comicyear', 'issues'), reverse=True)
except Exception as e:
logger.error('Unable to retrieve results from ComicVine: %s' % e)
if mylar.CONFIG.COMICVINE_API is None:
logger.error('You NEED to set a ComicVine API key prior to adding anything. It\'s Free - Go get one!')
return
return serve_template(templatename="searchresults.html", title='Search Results for: "' + name + '"', searchresults=searchresults, type=type, imported=None, ogcname=None, name=name, serinfo=serinfo)
searchit.exposed = True
def addComic(self, comicid, comicname=None, comicyear=None, comicimage=None, comicissues=None, comicpublisher=None, imported=None, ogcname=None, serinfo=None):
myDB = db.DBConnection()
if imported == "confirm":
# if it's coming from the importer and it's just for confirmation, record the right selection and break.
# if it's 'confirmed' coming in as the value for imported
# the ogcname will be the original comicid that is either correct/incorrect (doesn't matter which)
#confirmedid is the selected series (comicid) with the letter C at the beginning to denote Confirmed.
# then sql the original comicid which will hit on all the results for the given series.
# iterate through, and overwrite the existing watchmatch with the new chosen 'C' + comicid value
confirmedid = "C" + str(comicid)
confirms = myDB.select("SELECT * FROM importresults WHERE WatchMatch=?", [ogcname])
if confirms is None:
logger.Error("There are no results that match...this is an ERROR.")
else:
for confirm in confirms:
controlValue = {"impID": confirm['impID']}
newValue = {"WatchMatch": str(confirmedid)}
myDB.upsert("importresults", newValue, controlValue)
self.importResults()
return
elif imported == 'futurecheck':
print 'serinfo:' + str(serinfo)
logger.info('selected comicid of : ' + str(comicid) + ' [ ' + comicname + ' (' + str(comicyear) + ') ]')
ser = []
ser.append({"comicname": comicname,
"comicyear": comicyear,
"comicissues": comicissues,
"comicpublisher": comicpublisher,
"IssueDate": serinfo[0]['IssueDate'],
"IssueNumber": serinfo[0]['IssueNumber']})
weeklypull.future_check_add(comicid, ser)
sresults = []
cresults = []
mismatch = "no"
#print ("comicid: " + str(comicid))
#print ("comicname: " + str(comicname))
#print ("comicyear: " + str(comicyear))
#print ("comicissues: " + str(comicissues))
#print ("comicimage: " + str(comicimage))
if not mylar.CONFIG.CV_ONLY:
#here we test for exception matches (ie. comics spanning more than one volume, known mismatches, etc).
CV_EXcomicid = myDB.selectone("SELECT * from exceptions WHERE ComicID=?", [comicid]).fetchone()
if CV_EXcomicid is None: # pass #
gcdinfo=parseit.GCDScraper(comicname, comicyear, comicissues, comicid, quickmatch="yes")
if gcdinfo == "No Match":
#when it no matches, the image will always be blank...let's fix it.
cvdata = mylar.cv.getComic(comicid, 'comic')
comicimage = cvdata['ComicImage']
updater.no_searchresults(comicid)
nomatch = "true"
u_comicname = comicname.encode('utf-8').strip()
logger.info("I couldn't find an exact match for " + u_comicname + " (" + str(comicyear) + ") - gathering data for Error-Checking screen (this could take a minute)...")
i = 0
loopie, cnt = parseit.ComChk(comicname, comicyear, comicpublisher, comicissues, comicid)
logger.info("total count : " + str(cnt))
while (i < cnt):
try:
stoopie = loopie['comchkchoice'][i]
except (IndexError, TypeError):
break
cresults.append({
'ComicID': stoopie['ComicID'],
'ComicName': stoopie['ComicName'].decode('utf-8', 'replace'),
'ComicYear': stoopie['ComicYear'],
'ComicIssues': stoopie['ComicIssues'],
'ComicURL': stoopie['ComicURL'],
'ComicPublisher': stoopie['ComicPublisher'].decode('utf-8', 'replace'),
'GCDID': stoopie['GCDID']
})
i+=1
if imported != 'None':
#if it's from an import and it has to go through the UEC, return the values
#to the calling function and have that return the template
return cresults
else:
return serve_template(templatename="searchfix.html", title="Error Check", comicname=comicname, comicid=comicid, comicyear=comicyear, comicimage=comicimage, comicissues=comicissues, cresults=cresults, imported=None, ogcname=None)
else:
nomatch = "false"
logger.info(u"Quick match success..continuing.")
else:
if CV_EXcomicid['variloop'] == '99':
logger.info(u"mismatched name...autocorrecting to correct GID and auto-adding.")
mismatch = "yes"
if CV_EXcomicid['NewComicID'] == 'none':
logger.info(u"multi-volume series detected")
testspx = CV_EXcomicid['GComicID'].split('/')
for exc in testspx:
fakeit = parseit.GCDAdd(testspx)
howmany = int(CV_EXcomicid['variloop'])
t = 0
while (t <= howmany):
try:
sres = fakeit['serieschoice'][t]
except IndexError:
break
sresults.append({
'ComicID': sres['ComicID'],
'ComicName': sres['ComicName'],
'ComicYear': sres['ComicYear'],
'ComicIssues': sres['ComicIssues'],
'ComicPublisher': sres['ComicPublisher'],
'ComicCover': sres['ComicCover']
})
t+=1
#searchfix(-1).html is for misnamed comics and wrong years.
#searchfix-2.html is for comics that span multiple volumes.
return serve_template(templatename="searchfix-2.html", title="In-Depth Results", sresults=sresults)
#print ("imported is: " + str(imported))
threading.Thread(target=importer.addComictoDB, args=[comicid, mismatch, None, imported, ogcname]).start()
time.sleep(5) #wait 5s so the db can be populated enough to display the page - otherwise will return to home page if not enough info is loaded.
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % comicid)
addComic.exposed = True
def addbyid(self, comicid, calledby=None, imported=None, ogcname=None, nothread=False):
mismatch = "no"
logger.info('Attempting to add directly by ComicVineID: ' + str(comicid))
if comicid.startswith('4050-'): comicid = re.sub('4050-', '', comicid)
if nothread is False:
threading.Thread(target=importer.addComictoDB, args=[comicid, mismatch, None, imported, ogcname]).start()
else:
return importer.addComictoDB(comicid, mismatch, None, imported, ogcname)
if calledby == True or calledby == 'True':
return
elif calledby == 'web-import':
raise cherrypy.HTTPRedirect("importResults")
else:
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % comicid)
addbyid.exposed = True
def addStoryArc_thread(self, **kwargs):
threading.Thread(target=self.addStoryArc, kwargs=kwargs).start()
addStoryArc_thread.exposed = True
def addStoryArc(self, arcid, arcrefresh=False, cvarcid=None, arclist=None, storyarcname=None, storyarcyear=None, storyarcpublisher=None, storyarcissues=None, desc=None, image=None):
# used when a choice is selected to 'add story arc' via the searchresults screen (via the story arc search).
# arclist contains ALL the issueid's in sequence, along with the issue titles.
# call the function within cv.py to grab all the issueid's and return all the issue data
module = '[STORY ARC]'
myDB = db.DBConnection()
#check if it already exists.
if cvarcid is None:
arc_chk = myDB.select('SELECT * FROM storyarcs WHERE StoryArcID=?', [arcid])
else:
arc_chk = myDB.select('SELECT * FROM storyarcs WHERE CV_ArcID=?', [cvarcid])
if arc_chk is None:
if arcrefresh:
logger.warn(module + ' Unable to retrieve Story Arc ComicVine ID from the db. Unable to refresh Story Arc at this time. You probably have to delete/readd the story arc this one time for Refreshing to work properly.')
return
else:
logger.fdebug(module + ' No match in db based on ComicVine ID. Making sure and checking against Story Arc Name.')
arc_chk = myDB.select('SELECT * FROM storyarcs WHERE StoryArc=?', [storyarcname])
if arc_chk is None:
logger.warn(module + ' ' + storyarcname + ' already exists on your Story Arc Watchlist!')
raise cherrypy.HTTPRedirect("readlist")
else:
if arcrefresh: #cvarcid must be present here as well..
logger.info(module + '[' + str(arcid) + '] Successfully found Story Arc ComicVine ID [4045-' + str(cvarcid) + '] within db. Preparing to refresh Story Arc.')
# we need to store the existing arc values that are in the db, so we don't create duplicate entries or mess up items.
iss_arcids = []
for issarc in arc_chk:
iss_arcids.append({"IssueArcID": issarc['IssueArcID'],
"IssueID": issarc['IssueID'],
"Manual": issarc['Manual']})
arcinfo = mb.storyarcinfo(cvarcid)
if len(arcinfo) > 1:
arclist = arcinfo['arclist']
else:
logger.warn(module + ' Unable to retrieve issue details at this time. Something is probably wrong.')
return
# else:
# logger.warn(module + ' ' + storyarcname + ' already exists on your Story Arc Watchlist.')
# raise cherrypy.HTTPRedirect("readlist")
#check to makes sure storyarcs dir is present in cache in order to save the images...
if not os.path.isdir(os.path.join(mylar.CONFIG.CACHE_DIR, 'storyarcs')):
checkdirectory = filechecker.validateAndCreateDirectory(os.path.join(mylar.CONFIG.CACHE_DIR, 'storyarcs'), True)
if not checkdirectory:
logger.warn('Error trying to validate/create cache storyarc directory. Aborting this process at this time.')
return
coverfile = os.path.join(mylar.CONFIG.CACHE_DIR, 'storyarcs', str(cvarcid) + "-banner.jpg")
if mylar.CONFIG.CVAPI_RATE is None or mylar.CONFIG.CVAPI_RATE < 2:
time.sleep(2)
else:
time.sleep(mylar.CONFIG.CVAPI_RATE)
logger.info('Attempting to retrieve the comic image for series')
if arcrefresh:
imageurl = arcinfo['comicimage']
else:
imageurl = image
logger.info('imageurl: %s' % imageurl)
try:
r = requests.get(imageurl, params=None, stream=True, verify=mylar.CONFIG.CV_VERIFY, headers=mylar.CV_HEADERS)
except Exception, e:
logger.warn('Unable to download image from CV URL link - possibly no arc picture is present: %s' % imageurl)
else:
logger.fdebug('comic image retrieval status code: %s' % r.status_code)
if str(r.status_code) != '200':
logger.warn('Unable to download image from CV URL link: %s [Status Code returned: %s]' % (imageurl, r.status_code))
else:
if r.headers.get('Content-Encoding') == 'gzip':
import gzip
from StringIO import StringIO
buf = StringIO(r.content)
f = gzip.GzipFile(fileobj=buf)
with open(coverfile, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
arc_results = mylar.cv.getComic(comicid=None, type='issue', arcid=arcid, arclist=arclist)
logger.fdebug('%s Arcresults: %s' % (module, arc_results))
logger.fdebug('%s Arclist: %s' % (module, arclist))
if len(arc_results) > 0:
import random
issuedata = []
if storyarcissues is None:
storyarcissues = len(arc_results['issuechoice'])
if arcid is None:
storyarcid = str(random.randint(1000,9999)) + str(storyarcissues)
else:
storyarcid = arcid
n = 0
cidlist = ''
iscnt = int(storyarcissues)
while (n <= iscnt):
try:
arcval = arc_results['issuechoice'][n]
except IndexError:
break
comicname = arcval['ComicName']
st_d = mylar.filechecker.FileChecker(watchcomic=comicname)
st_dyninfo = st_d.dynamic_replace(comicname)
dynamic_name = re.sub('[\|\s]','', st_dyninfo['mod_seriesname'].lower()).strip()
issname = arcval['Issue_Name']
issid = str(arcval['IssueID'])
comicid = str(arcval['ComicID'])
#--- this needs to get changed so comicid within a comicid doesn't exist (ie. 3092 is IN 33092)
cid_count = cidlist.count(comicid) +1
a_end = 0
i = 0
while i < cid_count:
a = cidlist.find(comicid, a_end)
a_end = cidlist.find('|',a)
if a_end == -1: a_end = len(cidlist)
a_length = cidlist[a:a_end-1]
if a == -1 and len(a_length) != len(comicid):
if n == 0:
cidlist += str(comicid)
else:
cidlist += '|' + str(comicid)
break
i+=1
#don't recreate the st_issueid if it's a refresh and the issueid already exists (will create duplicates otherwise)
st_issueid = None
manual_mod = None
if arcrefresh:
for aid in iss_arcids:
if aid['IssueID'] == issid:
st_issueid = aid['IssueArcID']
manual_mod = aid['Manual']
break
if st_issueid is None:
st_issueid = str(storyarcid) + "_" + str(random.randint(1000,9999))
issnum = arcval['Issue_Number']
issdate = str(arcval['Issue_Date'])
digitaldate = str(arcval['Digital_Date'])
storedate = str(arcval['Store_Date'])
int_issnum = helpers.issuedigits(issnum)
#verify the reading order if present.
findorder = arclist.find(issid)
if findorder != -1:
ros = arclist.find('|',findorder+1)
if ros != -1:
roslen = arclist[findorder:ros]
else:
#last entry doesn't have a trailling '|'
roslen = arclist[findorder:]
rosre = re.sub(issid,'', roslen)
readingorder = int(re.sub('[\,\|]','', rosre).strip())
else:
readingorder = 0
logger.fdebug('[%s] issueid: %s - findorder#: %s' % (readingorder, issid, findorder))
issuedata.append({"ComicID": comicid,
"IssueID": issid,
"StoryArcID": storyarcid,
"IssueArcID": st_issueid,
"ComicName": comicname,
"DynamicName": dynamic_name,
"IssueName": issname,
"Issue_Number": issnum,
"IssueDate": issdate,
"ReleaseDate": storedate,
"DigitalDate": digitaldate,
"ReadingOrder": readingorder, #n +1,
"Int_IssueNumber": int_issnum,
"Manual": manual_mod})
n+=1
comicid_results = mylar.cv.getComic(comicid=None, type='comicyears', comicidlist=cidlist)
logger.fdebug('%s Initiating issue updating - just the info' % module)
for AD in issuedata:
seriesYear = 'None'
issuePublisher = 'None'
seriesVolume = 'None'
if AD['IssueName'] is None:
IssueName = 'None'
else:
IssueName = AD['IssueName'][:70]
for cid in comicid_results:
if cid['ComicID'] == AD['ComicID']:
seriesYear = cid['SeriesYear']
issuePublisher = cid['Publisher']
seriesVolume = cid['Volume']
bookType = cid['Type']
seriesAliases = cid['Aliases']
if storyarcpublisher is None:
#assume that the arc is the same
storyarcpublisher = issuePublisher
break
newCtrl = {"IssueID": AD['IssueID'],
"StoryArcID": AD['StoryArcID']}
newVals = {"ComicID": AD['ComicID'],
"IssueArcID": AD['IssueArcID'],
"StoryArc": storyarcname,
"ComicName": AD['ComicName'],
"Volume": seriesVolume,
"DynamicComicName": AD['DynamicName'],
"IssueName": IssueName,
"IssueNumber": AD['Issue_Number'],
"Publisher": storyarcpublisher,
"TotalIssues": storyarcissues,
"ReadingOrder": AD['ReadingOrder'],
"IssueDate": AD['IssueDate'],
"ReleaseDate": AD['ReleaseDate'],
"DigitalDate": AD['DigitalDate'],
"SeriesYear": seriesYear,
"IssuePublisher": issuePublisher,
"CV_ArcID": arcid,
"Int_IssueNumber": AD['Int_IssueNumber'],
"Type": bookType,
"Aliases": seriesAliases,
"Manual": AD['Manual']}
myDB.upsert("storyarcs", newVals, newCtrl)
#run the Search for Watchlist matches now.
logger.fdebug(module + ' Now searching your watchlist for matches belonging to this story arc.')
self.ArcWatchlist(storyarcid)
if arcrefresh:
logger.info('%s Successfully Refreshed %s' % (module, storyarcname))
return
else:
logger.info('%s Successfully Added %s' % (module, storyarcname))
raise cherrypy.HTTPRedirect("detailStoryArc?StoryArcID=%s&StoryArcName=%s" % (storyarcid, storyarcname))
addStoryArc.exposed = True
def wanted_Export(self,mode):
import unicodedata
myDB = db.DBConnection()
wantlist = myDB.select("select b.ComicName, b.ComicYear, a.Issue_Number, a.IssueDate, a.ComicID, a.IssueID from issues a inner join comics b on a.ComicID=b.ComicID where a.status=? and b.ComicName is not NULL", [mode])
if wantlist is None:
logger.info("There aren't any issues marked as " + mode + ". Aborting Export.")
return
#write out a wanted_list.csv
logger.info("gathered data - writing to csv...")
wanted_file = os.path.join(mylar.DATA_DIR, str(mode) + "_list.csv")
if os.path.exists(wanted_file):
try:
os.remove(wanted_file)
except (OSError, IOError):
wanted_file_new = os.path.join(mylar.DATA_DIR, str(mode) + '_list-1.csv')
logger.warn('%s already exists. Writing to: %s' % (wanted_file, wanted_file_new))
wanted_file = wanted_file_new
wcount=0
with open(wanted_file, 'wb+') as f:
try:
fieldnames = ['SeriesName','SeriesYear','IssueNumber','IssueDate','ComicID','IssueID']
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for want in wantlist:
writer.writerow({'SeriesName': want['ComicName'],
'SeriesYear': want['ComicYear'],
'IssueNumber': want['Issue_Number'],
'IssueDate': want['IssueDate'],
'ComicID': want['ComicID'],
'IssueID': want['IssueID']})
wcount += 1
except IOError as Argument:
logger.info("Error writing value to {}. {}".format(wanted_file, Argument))
except Exception as Argument:
logger.info("Unknown error: {}".format(Argument))
if wcount > 0:
logger.info('Successfully wrote to csv file %s entries from your %s list.' % (wcount, mode))
else:
logger.info('Nothing written to csv file for your %s list.' % mode)
raise cherrypy.HTTPRedirect("home")
wanted_Export.exposed = True
def from_Exceptions(self, comicid, gcdid, comicname=None, comicyear=None, comicissues=None, comicpublisher=None, imported=None, ogcname=None):
import unicodedata
mismatch = "yes"
#write it to the custom_exceptions.csv and reload it so that importer will pick it up and do it's thing :)
#custom_exceptions in this format...
#99, (comicid), (gcdid), none
logger.info("saving new information into custom_exceptions.csv...")
except_info = "none #" + str(comicname) + "-(" + str(comicyear) + ")\n"
except_file = os.path.join(mylar.DATA_DIR, "custom_exceptions.csv")
if not os.path.exists(except_file):
try:
csvfile = open(str(except_file), 'rb')
csvfile.close()
except (OSError, IOError):
logger.error("Could not locate " + str(except_file) + " file. Make sure it's in datadir: " + mylar.DATA_DIR + " with proper permissions.")
return
exceptln = "99," + str(comicid) + "," + str(gcdid) + "," + str(except_info)
exceptline = exceptln.decode('utf-8', 'ignore')
with open(str(except_file), 'a') as f:
#f.write('%s,%s,%s,%s\n' % ("99", comicid, gcdid, except_info)
f.write('%s\n' % (exceptline.encode('ascii', 'replace').strip()))
logger.info("re-loading csv file so it's all nice and current.")
mylar.csv_load()
if imported:
threading.Thread(target=importer.addComictoDB, args=[comicid, mismatch, None, imported, ogcname]).start()
else:
threading.Thread(target=importer.addComictoDB, args=[comicid, mismatch]).start()
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % comicid)
from_Exceptions.exposed = True
def GCDaddComic(self, comicid, comicname=None, comicyear=None, comicissues=None, comiccover=None, comicpublisher=None):
#since we already know most of the info, let's add it to the db so we can reference it later.
myDB = db.DBConnection()
gcomicid = "G" + str(comicid)
comicyear_len = comicyear.find(' ', 2)
comyear = comicyear[comicyear_len +1:comicyear_len +5]
if comyear.isdigit():
logger.fdebug("Series year set to : " + str(comyear))
else:
logger.fdebug("Invalid Series year detected - trying to adjust from " + str(comyear))
#comicyear_len above will trap wrong year if it's 10 October 2010 - etc ( 2000 AD)...
find_comicyear = comicyear.split()
for i in find_comicyear:
if len(i) == 4:
logger.fdebug("Series year detected as : " + str(i))
comyear = str(i)
continue
logger.fdebug("Series year set to: " + str(comyear))
controlValueDict = {'ComicID': gcomicid}
newValueDict = {'ComicName': comicname,
'ComicYear': comyear,
'ComicPublished': comicyear,
'ComicPublisher': comicpublisher,
'ComicImage': comiccover,
'Total': comicissues}
myDB.upsert("comics", newValueDict, controlValueDict)
threading.Thread(target=importer.GCDimport, args=[gcomicid]).start()
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % gcomicid)
GCDaddComic.exposed = True
def post_process(self, nzb_name, nzb_folder, failed=False, apc_version=None, comicrn_version=None):
if all([nzb_name != 'Manual Run', nzb_name != 'Manual+Run']):
if comicrn_version is None and apc_version is None:
logger.warn('ComicRN should be v' + str(mylar.STATIC_COMICRN_VERSION) + ' and autoProcessComics.py should be v' + str(mylar.STATIC_APC_VERSION) + ', but they are not and are out of date. Post-Processing may or may not work.')
elif comicrn_version is None or comicrn_version != mylar.STATIC_COMICRN_VERSION:
if comicrn_version == 'None':
comicrn_version = "0"
logger.warn('Your ComicRN.py script should be v' + str(mylar.STATIC_COMICRN_VERSION) + ', but is v' + str(comicrn_version) + ' and is out of date. Things may still work - but you are taking your chances.')
elif apc_version is None or apc_version != mylar.STATIC_APC_VERSION:
if apc_version == 'None':
apc_version = "0"
if mylar.CONFIG.AUTHENTICATION == 2:
logger.warn('YOU NEED TO UPDATE YOUR autoProcessComics.py file in order to use this option with the Forms Login enabled due to security.')
logger.warn('Your autoProcessComics.py script should be v' + str(mylar.STATIC_APC_VERSION) + ', but is v' + str(apc_version) + ' and is out of date. Odds are something is gonna fail - you should update it.')
else:
logger.info('ComicRN.py version: ' + str(comicrn_version) + ' -- autoProcessComics.py version: ' + str(apc_version))
import Queue
logger.info('Starting postprocessing for : ' + nzb_name)
if failed == '0':
failed = False
elif failed == '1':
failed = True
queue = Queue.Queue()
retry_outside = False
if not failed:
PostProcess = PostProcessor.PostProcessor(nzb_name, nzb_folder, queue=queue)
if nzb_name == 'Manual Run' or nzb_name == 'Manual+Run':
threading.Thread(target=PostProcess.Process).start()
#raise cherrypy.HTTPRedirect("home")
else:
thread_ = threading.Thread(target=PostProcess.Process, name="Post-Processing")
thread_.start()
thread_.join()
chk = queue.get()
while True:
if chk[0]['mode'] == 'fail':
yield chk[0]['self.log']
logger.info('Initiating Failed Download handling')
if chk[0]['annchk'] == 'no': mode = 'want'
else: mode = 'want_ann'
failed = True
break
elif chk[0]['mode'] == 'stop':
yield chk[0]['self.log']
break
elif chk[0]['mode'] == 'outside':
yield chk[0]['self.log']
retry_outside = True
break
else:
logger.error('mode is unsupported: ' + chk[0]['mode'])
yield chk[0]['self.log']
break
if failed:
if mylar.CONFIG.FAILED_DOWNLOAD_HANDLING is True:
#drop the if-else continuation so we can drop down to this from the above if statement.
logger.info('Initiating Failed Download handling for this download.')
FailProcess = Failed.FailedProcessor(nzb_name=nzb_name, nzb_folder=nzb_folder, queue=queue)
thread_ = threading.Thread(target=FailProcess.Process, name="FAILED Post-Processing")
thread_.start()
thread_.join()
failchk = queue.get()
if failchk[0]['mode'] == 'retry':
yield failchk[0]['self.log']
logger.info('Attempting to return to search module with ' + str(failchk[0]['issueid']))
if failchk[0]['annchk'] == 'no': mode = 'want'
else: mode = 'want_ann'
self.queueit(mode=mode, ComicName=failchk[0]['comicname'], ComicIssue=failchk[0]['issuenumber'], ComicID=failchk[0]['comicid'], IssueID=failchk[0]['issueid'], manualsearch=True)
elif failchk[0]['mode'] == 'stop':
yield failchk[0]['self.log']
else:
logger.error('mode is unsupported: ' + failchk[0]['mode'])
yield failchk[0]['self.log']
else:
logger.warn('Failed Download Handling is not enabled. Leaving Failed Download as-is.')
if retry_outside:
PostProcess = PostProcessor.PostProcessor('Manual Run', nzb_folder, queue=queue)
thread_ = threading.Thread(target=PostProcess.Process, name="Post-Processing")
thread_.start()
thread_.join()
chk = queue.get()
while True:
if chk[0]['mode'] == 'fail':
yield chk[0]['self.log']
logger.info('Initiating Failed Download handling')
if chk[0]['annchk'] == 'no': mode = 'want'
else: mode = 'want_ann'
failed = True
break
elif chk[0]['mode'] == 'stop':
yield chk[0]['self.log']
break
else:
logger.error('mode is unsupported: ' + chk[0]['mode'])
yield chk[0]['self.log']
break
return
post_process.exposed = True
def pauseSeries(self, ComicID):
logger.info(u"Pausing comic: " + ComicID)
myDB = db.DBConnection()
controlValueDict = {'ComicID': ComicID}
newValueDict = {'Status': 'Paused'}
myDB.upsert("comics", newValueDict, controlValueDict)
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % ComicID)
pauseSeries.exposed = True
def resumeSeries(self, ComicID):
logger.info(u"Resuming comic: " + ComicID)
myDB = db.DBConnection()
controlValueDict = {'ComicID': ComicID}
newValueDict = {'Status': 'Active'}
myDB.upsert("comics", newValueDict, controlValueDict)
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % ComicID)
resumeSeries.exposed = True
def deleteSeries(self, ComicID, delete_dir=None):
myDB = db.DBConnection()
comic = myDB.selectone('SELECT * from comics WHERE ComicID=?', [ComicID]).fetchone()
if comic['ComicName'] is None: ComicName = "None"
else: ComicName = comic['ComicName']
seriesdir = comic['ComicLocation']
seriesyear = comic['ComicYear']
seriesvol = comic['ComicVersion']
logger.info(u"Deleting all traces of Comic: " + ComicName)
myDB.action('DELETE from comics WHERE ComicID=?', [ComicID])
myDB.action('DELETE from issues WHERE ComicID=?', [ComicID])
if mylar.CONFIG.ANNUALS_ON:
myDB.action('DELETE from annuals WHERE ComicID=?', [ComicID])
myDB.action('DELETE from upcoming WHERE ComicID=?', [ComicID])
if delete_dir: #mylar.CONFIG.DELETE_REMOVE_DIR:
logger.fdebug('Remove directory on series removal enabled.')
if os.path.exists(seriesdir):
logger.fdebug('Attempting to remove the directory and contents of : ' + seriesdir)
try:
shutil.rmtree(seriesdir)
except:
logger.warn('Unable to remove directory after removing series from Mylar.')
else:
logger.info('Successfully removed directory: %s' % (seriesdir))
else:
logger.warn('Unable to remove directory as it does not exist in : ' + seriesdir)
myDB.action('DELETE from readlist WHERE ComicID=?', [ComicID])
logger.info('Successful deletion of %s %s (%s) from your watchlist' % (ComicName, seriesvol, seriesyear))
helpers.ComicSort(sequence='update')
raise cherrypy.HTTPRedirect("home")
deleteSeries.exposed = True
def wipenzblog(self, ComicID=None, IssueID=None):
myDB = db.DBConnection()
if ComicID is None:
logger.fdebug("Wiping NZBLOG in it's entirety. You should NOT be downloading while doing this or else you'll lose the log for the download.")
myDB.action('DROP table nzblog')
logger.fdebug("Deleted nzblog table.")
myDB.action('CREATE TABLE IF NOT EXISTS nzblog (IssueID TEXT, NZBName TEXT, SARC TEXT, PROVIDER TEXT, ID TEXT, AltNZBName TEXT, OneOff TEXT)')
logger.fdebug("Re-created nzblog table.")
raise cherrypy.HTTPRedirect("history")
if IssueID:
logger.fdebug('Removing all download history for the given IssueID. This should allow post-processing to finish for the given IssueID.')
myDB.action('DELETE FROM nzblog WHERE IssueID=?', [IssueID])
logger.fdebug('Successfully removed all entries in the download log for IssueID: ' + str(IssueID))
raise cherrypy.HTTPRedirect("history")
wipenzblog.exposed = True
def refreshSeries(self, ComicID):
comicsToAdd = [ComicID]
logger.fdebug("Refreshing comic: %s" % comicsToAdd)
#myDB = db.DBConnection()
#myDB.upsert('comics', {'Status': 'Loading'}, {'ComicID': ComicID})
#threading.Thread(target=updater.dbUpdate, args=[comicsToAdd,'refresh']).start()
updater.dbUpdate(comicsToAdd, 'refresh')
refreshSeries.exposed = True
def issue_edit(self, id, value):
logger.fdebug('id: ' + str(id))
logger.fdebug('value: ' + str(value))
comicid = id[:id.find('.')]
logger.fdebug('comicid:' + str(comicid))
issueid = id[id.find('.') +1:]
logger.fdebug('issueid:' + str(issueid))
myDB = db.DBConnection()
comicchk = myDB.selectone('SELECT ComicYear FROM comics WHERE ComicID=?', [comicid]).fetchone()
issuechk = myDB.selectone('SELECT * FROM issues WHERE IssueID=?', [issueid]).fetchone()
if issuechk is None:
logger.error('Cannot edit this for some reason - something is wrong.')
return
oldissuedate = issuechk['IssueDate']
seriesyear = comicchk['ComicYear']
issuenumber = issuechk['Issue_Number']
#check if the new date is in the correct format of yyyy-mm-dd
try:
valid_date = time.strptime(value, '%Y-%m-%d')
except ValueError:
logger.error('invalid date provided. Rejecting edit.')
return oldissuedate
#if the new issue year is less than the series year - reject it.
if value[:4] < seriesyear:
logger.error('Series year of ' + str(seriesyear) + ' is less than new issue date of ' + str(value[:4]))
return oldissuedate
newVal = {"IssueDate": value,
"IssueDate_Edit": oldissuedate}
ctrlVal = {"IssueID": issueid}
myDB.upsert("issues", newVal, ctrlVal)
logger.info('Updated Issue Date for issue #' + str(issuenumber))
return value
issue_edit.exposed=True
def force_rss(self):
logger.info('Attempting to run RSS Check Forcibly')
forcethis = mylar.rsscheckit.tehMain()
threading.Thread(target=forcethis.run, args=[True]).start()
force_rss.exposed = True
def markannuals(self, ann_action=None, **args):
self.markissues(ann_action, **args)
markannuals.exposed = True
def markissues(self, action=None, **args):
myDB = db.DBConnection()
issuesToAdd = []
issuestoArchive = []
if action == 'WantedNew':
newaction = 'Wanted'
else:
newaction = action
for IssueID in args:
if any([IssueID is None, 'issue_table' in IssueID, 'history_table' in IssueID, 'manage_issues' in IssueID, 'issue_table_length' in IssueID, 'issues' in IssueID, 'annuals' in IssueID, 'annual_table_length' in IssueID]):
continue
else:
mi = myDB.selectone("SELECT * FROM issues WHERE IssueID=?", [IssueID]).fetchone()
annchk = 'no'
if mi is None:
if mylar.CONFIG.ANNUALS_ON:
mi = myDB.selectone("SELECT * FROM annuals WHERE IssueID=?", [IssueID]).fetchone()
comicname = mi['ReleaseComicName']
annchk = 'yes'
else:
comicname = mi['ComicName']
miyr = myDB.selectone("SELECT ComicYear FROM comics WHERE ComicID=?", [mi['ComicID']]).fetchone()
if action == 'Downloaded':
if mi['Status'] == "Skipped" or mi['Status'] == "Wanted":
logger.fdebug(u"Cannot change status to %s as comic is not Snatched or Downloaded" % (newaction))
continue
elif action == 'Archived':
logger.fdebug(u"Marking %s %s as %s" % (comicname, mi['Issue_Number'], newaction))
#updater.forceRescan(mi['ComicID'])
issuestoArchive.append(IssueID)
elif action == 'Wanted' or action == 'Retry':
if mi['Status'] == 'Wanted':
logger.fdebug('Issue already set to Wanted status - no need to change it again.')
continue
if action == 'Retry': newaction = 'Wanted'
logger.fdebug(u"Marking %s %s as %s" % (comicname, mi['Issue_Number'], newaction))
issuesToAdd.append(IssueID)
elif action == 'Skipped':
logger.fdebug(u"Marking " + str(IssueID) + " as Skipped")
elif action == 'Clear':
myDB.action("DELETE FROM snatched WHERE IssueID=?", [IssueID])
elif action == 'Failed' and mylar.CONFIG.FAILED_DOWNLOAD_HANDLING:
logger.fdebug('Marking [' + comicname + '] : ' + str(IssueID) + ' as Failed. Sending to failed download handler.')
failedcomicid = mi['ComicID']
failedissueid = IssueID
break
controlValueDict = {"IssueID": IssueID}
newValueDict = {"Status": newaction}
if annchk == 'yes':
myDB.upsert("annuals", newValueDict, controlValueDict)
else:
myDB.upsert("issues", newValueDict, controlValueDict)
logger.fdebug("updated...to " + str(newaction))
if action == 'Failed' and mylar.CONFIG.FAILED_DOWNLOAD_HANDLING:
self.failed_handling(failedcomicid, failedissueid)
if len(issuestoArchive) > 0:
updater.forceRescan(mi['ComicID'])
if len(issuesToAdd) > 0:
logger.fdebug("Marking issues: %s as Wanted" % (issuesToAdd))
threading.Thread(target=search.searchIssueIDList, args=[issuesToAdd]).start()
#raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % mi['ComicID'])
markissues.exposed = True
def markentries(self, action=None, **args):
myDB = db.DBConnection()
cnt = 0
for ID in args:
logger.info(ID)
if any([ID is None, 'manage_failed_length' in ID]):
continue
else:
myDB.action("DELETE FROM Failed WHERE ID=?", [ID])
cnt+=1
logger.info('[DB FAILED CLEANSING] Cleared ' + str(cnt) + ' entries from the Failed DB so they will now be downloaded if available/working.')
markentries.exposed = True
def retryit(self, **kwargs):
threading.Thread(target=self.retryissue, kwargs=kwargs).start()
retryit.exposed = True
def retryissue(self, ComicName, ComicID, IssueID, IssueNumber, ReleaseComicID=None, ComicYear=None, redirect=None):
logger.info('ComicID:' + str(ComicID))
logger.info('Retrying : ' + str(IssueID))
# mode = either series or annual (want vs. want_ann)
#To retry the exact download again - we already have the nzb/torrent name stored in the nzblog.
#0 - Change status to Retrying.
#1 - we need to search the snatched table for the relevant information (since it HAS to be in snatched status)
#2 - we need to reference the ID from the snatched table to the nzblog table
# - if it doesn't match, then it's an invalid retry.
# - if it does match, we get the nzbname/torrent name and provider info
#3 - if it's an nzb - we recreate the sab/nzbget url and resubmit it directly.
# - if it's a torrent - we redownload the torrent and flip it to the watchdir on the local / seedbox.
#4 - Change status to Snatched.
myDB = db.DBConnection()
chk_snatch = myDB.select('SELECT * FROM snatched WHERE IssueID=?', [IssueID])
if chk_snatch is None:
logger.info('Unable to locate how issue was downloaded (name, provider). Cannot continue.')
return
providers_snatched = []
confirmedsnatch = False
for cs in chk_snatch:
if cs['Provider'] == 'CBT' or cs['Provider'] == 'KAT':
logger.info('Invalid provider attached to download (' + cs['Provider'] + '). I cannot find this on 32P, so ignoring this result.')
elif cs['Status'] == 'Snatched':
logger.info('Located snatched download:')
logger.info('--Referencing : ' + cs['Provider'] + ' @ ' + str(cs['DateAdded']))
providers_snatched.append({'Provider': cs['Provider'],
'DateAdded': cs['DateAdded']})
confirmedsnatch = True
elif (cs['Status'] == 'Post-Processed' or cs['Status'] == 'Downloaded') and confirmedsnatch == True:
logger.info('Issue has already been Snatched, Downloaded & Post-Processed.')
logger.info('You should be using Manual Search or Mark Wanted - not retry the same download.')
#return
if len(providers_snatched) == 0:
return
chk_logresults = []
for ps in sorted(providers_snatched, key=itemgetter('DateAdded', 'Provider'), reverse=True):
try:
Provider_sql = '%' + ps['Provider'] + '%'
chk_the_log = myDB.selectone('SELECT * FROM nzblog WHERE IssueID=? AND Provider like (?)', [IssueID, Provider_sql]).fetchone()
except:
logger.warn('Unable to locate provider reference for attempted Retry. Will see if I can just get the last attempted download.')
chk_the_log = myDB.selectone('SELECT * FROM nzblog WHERE IssueID=? and Provider != "CBT" and Provider != "KAT"', [IssueID]).fetchone()
if chk_the_log is None:
if len(providers_snatched) == 1:
logger.info('Unable to locate provider information ' + ps['Provider'] + ' from nzblog - if you wiped the log, you have to search/download as per normal')
return
else:
logger.info('Unable to locate provider information ' + ps['Provider'] + ' from nzblog. Checking additional providers that came back as being used to download this issue')
continue
else:
chk_logresults.append({'NZBName': chk_the_log['NZBName'],
'ID': chk_the_log['ID'],
'PROVIDER': chk_the_log['PROVIDER']})
if all([ComicYear is not None, ComicYear != 'None']) and all([IssueID is not None, IssueID != 'None']):
getYear = myDB.selectone('SELECT IssueDate, ReleaseDate FROM Issues WHERE IssueID=?', [IssueID]).fetchone()
if getYear is None:
logger.warn('Unable to retrieve valid Issue Date for Retry of Issue (Try to refresh the series and then try again.')
return
if getYear['IssueDate'][:4] == '0000':
if getYear['ReleaseDate'][:4] == '0000':
logger.warn('Unable to retrieve valid Issue Date for Retry of Issue (Try to refresh the series and then try again.')
return
else:
ComicYear = getYear['ReleaseDate'][:4]
else:
ComicYear = getYear['IssueDate'][:4]
for chk_log in chk_logresults:
nzbname = chk_log['NZBName']
id = chk_log['ID']
fullprov = chk_log['PROVIDER'] #the full newznab name if it exists will appear here as 'sitename (newznab)'
#now we break it down by provider to recreate the link.
#torrents first.
if any([fullprov == '32P', fullprov == 'WWT', fullprov == 'DEM']):
if not mylar.CONFIG.ENABLE_TORRENT_SEARCH:
logger.error('Torrent Providers are not enabled - unable to process retry request until provider is re-enabled.')
continue
if fullprov == '32P':
if not mylar.CONFIG.ENABLE_32P:
logger.error('32P is not enabled - unable to process retry request until provider is re-enabled.')
continue
elif any([fullprov == 'WWT', fullprov == 'DEM']):
if not mylar.CONFIG.ENABLE_PUBLIC:
logger.error('Public Torrents are not enabled - unable to process retry request until provider is re-enabled.')
continue
logger.fdebug("sending .torrent to watchdir.")
logger.fdebug("ComicName:" + ComicName)
logger.fdebug("Torrent Provider:" + fullprov)
logger.fdebug("Torrent ID:" + str(id))
rcheck = mylar.rsscheck.torsend2client(ComicName, IssueNumber, ComicYear, id, fullprov)
if rcheck == "fail":
logger.error("Unable to send torrent - check logs and settings.")
continue
else:
if any([mylar.USE_RTORRENT, mylar.USE_DELUGE]) and mylar.CONFIG.AUTO_SNATCH:
mylar.SNATCHED_QUEUE.put(rcheck['hash'])
elif mylar.CONFIG.ENABLE_SNATCH_SCRIPT:
#packs not supported on retry atm - Volume and Issuedate also not included due to limitations...
snatch_vars = {'comicinfo': {'comicname': ComicName,
'issuenumber': IssueNumber,
'seriesyear': ComicYear,
'comicid': ComicID,
'issueid': IssueID},
'pack': False,
'pack_numbers': None,
'pack_issuelist': None,
'provider': fullprov,
'method': 'torrent',
'clientmode': rcheck['clientmode'],
'torrentinfo': rcheck}
snatchitup = helpers.script_env('on-snatch',snatch_vars)
if snatchitup is True:
logger.info('Successfully submitted on-grab script as requested.')
else:
logger.info('Could not Successfully submit on-grab script as requested. Please check logs...')
logger.info('Successfully retried issue.')
break
else:
oneoff = False
chkthis = myDB.selectone('SELECT a.ComicID, a.ComicName, a.ComicVersion, a.ComicYear, b.IssueID, b.Issue_Number, b.IssueDate FROM comics as a INNER JOIN annuals as b ON a.ComicID = b.ComicID WHERE IssueID=?', [IssueID]).fetchone()
if chkthis is None:
chkthis = myDB.selectone('SELECT a.ComicID, a.ComicName, a.ComicVersion, a.ComicYear, b.IssueID, b.Issue_Number, b.IssueDate FROM comics as a INNER JOIN issues as b ON a.ComicID = b.ComicID WHERE IssueID=?', [IssueID]).fetchone()
if chkthis is None:
chkthis = myDB.selectone('SELECT ComicID, ComicName, year as ComicYear, IssueID, IssueNumber as Issue_number, weeknumber, year from oneoffhistory WHERE IssueID=?', [IssueID]).fetchone()
if chkthis is None:
logger.warn('Unable to locate previous snatch details (checked issues/annuals/one-offs). Retrying the snatch for this issue is unavailable.')
continue
else:
logger.fdebug('Successfully located issue as a one-off download initiated via pull-list. Let\'s do this....')
oneoff = True
modcomicname = chkthis['ComicName']
else:
modcomicname = chkthis['ComicName'] + ' Annual'
if oneoff is True:
weekchk = helpers.weekly_info(chkthis['weeknumber'], chkthis['year'])
IssueDate = weekchk['midweek']
ComicVersion = None
else:
IssueDate = chkthis['IssueDate']
ComicVersion = chkthis['ComicVersion']
comicinfo = []
comicinfo.append({"ComicName": chkthis['ComicName'],
"ComicVolume": ComicVersion,
"IssueNumber": chkthis['Issue_Number'],
"comyear": chkthis['ComicYear'],
"IssueDate": IssueDate,
"pack": False,
"modcomicname": modcomicname,
"oneoff": oneoff})
newznabinfo = None
link = None
if fullprov == 'nzb.su':
if not mylar.CONFIG.NZBSU:
logger.error('nzb.su is not enabled - unable to process retry request until provider is re-enabled.')
continue
# http://nzb.su/getnzb/ea1befdeee0affd663735b2b09010140.nzb&i=<uid>&r=<passkey>
link = 'http://nzb.su/getnzb/' + str(id) + '.nzb&i=' + str(mylar.CONFIG.NZBSU_UID) + '&r=' + str(mylar.CONFIG.NZBSU_APIKEY)
logger.info('fetched via nzb.su. Retrying the send : ' + str(link))
elif fullprov == 'dognzb':
if not mylar.CONFIG.DOGNZB:
logger.error('Dognzb is not enabled - unable to process retry request until provider is re-enabled.')
continue
# https://dognzb.cr/fetch/5931874bf7381b274f647712b796f0ac/<passkey>
link = 'https://dognzb.cr/fetch/' + str(id) + '/' + str(mylar.CONFIG.DOGNZB_APIKEY)
logger.info('fetched via dognzb. Retrying the send : ' + str(link))
elif fullprov == 'experimental':
if not mylar.CONFIG.EXPERIMENTAL:
logger.error('Experimental is not enabled - unable to process retry request until provider is re-enabled.')
continue
# http://nzbindex.nl/download/110818178
link = 'http://nzbindex.nl/download/' + str(id)
logger.info('fetched via experimental. Retrying the send : ' + str(link))
elif 'newznab' in fullprov:
if not mylar.CONFIG.NEWZNAB:
logger.error('Newznabs are not enabled - unable to process retry request until provider is re-enabled.')
continue
# http://192.168.2.2/getnzb/4323f9c567c260e3d9fc48e09462946c.nzb&i=<uid>&r=<passkey>
# trickier - we have to scroll through all the newznabs until we find a match.
logger.info('fetched via newnzab. Retrying the send.')
m = re.findall('[^()]+', fullprov)
tmpprov = m[0].strip()
for newznab_info in mylar.CONFIG.EXTRA_NEWZNABS:
if tmpprov.lower() in newznab_info[0].lower():
if (newznab_info[5] == '1' or newznab_info[5] == 1):
if newznab_info[1].endswith('/'):
newznab_host = newznab_info[1]
else:
newznab_host = newznab_info[1] + '/'
newznab_api = newznab_info[3]
newznab_uid = newznab_info[4]
link = str(newznab_host) + '/api?apikey=' + str(newznab_api) + '&t=get&id=' + str(id)
logger.info('newznab detected as : ' + str(newznab_info[0]) + ' @ ' + str(newznab_host))
logger.info('link : ' + str(link))
newznabinfo = (newznab_info[0], newznab_info[1], newznab_info[2], newznab_info[3], newznab_info[4])
else:
logger.error(str(newznab_info[0]) + ' is not enabled - unable to process retry request until provider is re-enabled.')
break
if link is not None:
sendit = search.searcher(fullprov, nzbname, comicinfo, link=link, IssueID=IssueID, ComicID=ComicID, tmpprov=fullprov, directsend=True, newznab=newznabinfo)
break
return
retryissue.exposed = True
def queueit(self, **kwargs):
threading.Thread(target=self.queueissue, kwargs=kwargs).start()
queueit.exposed = True
def queueissue(self, mode, ComicName=None, ComicID=None, ComicYear=None, ComicIssue=None, IssueID=None, new=False, redirect=None, SeriesYear=None, SARC=None, IssueArcID=None, manualsearch=None, Publisher=None, pullinfo=None, pullweek=None, pullyear=None, manual=False, ComicVersion=None, BookType=None):
logger.fdebug('ComicID: %s' % ComicID)
logger.fdebug('mode: %s' % mode)
now = datetime.datetime.now()
myDB = db.DBConnection()
#mode dictates type of queue - either 'want' for individual comics, or 'series' for series watchlist.
if ComicID is None and mode == 'series':
issue = None
raise cherrypy.HTTPRedirect("searchit?name=%s&issue=%s&mode=%s" % (ComicName, 'None', 'series'))
elif ComicID is None and mode == 'pullseries':
# we can limit the search by including the issue # and searching for
# comics that have X many issues
raise cherrypy.HTTPRedirect("searchit?name=%s&issue=%s&mode=%s" % (ComicName, 'None', 'pullseries'))
elif ComicID is None and mode == 'readlist':
# this is for marking individual comics from a readlist to be downloaded.
# Because there is no associated ComicID or IssueID, follow same pattern as in 'pullwant'
# except we know the Year
if len(ComicYear) > 4:
ComicYear = ComicYear[:4]
if SARC is None:
# it's just a readlist queue (no storyarc mode enabled)
SARC = True
IssueArcID = None
else:
logger.info('Story Arc : %s queueing selected issue...' % SARC)
logger.fdebug('IssueArcID : %s' % IssueArcID)
#try to load the issue dates - can now sideload issue details.
dateload = myDB.selectone('SELECT * FROM storyarcs WHERE IssueArcID=?', [IssueArcID]).fetchone()
if dateload is None:
IssueDate = None
ReleaseDate = None
Publisher = None
SeriesYear = None
else:
IssueDate = dateload['IssueDate']
ReleaseDate = dateload['ReleaseDate']
Publisher = dateload['IssuePublisher']
SeriesYear = dateload['SeriesYear']
BookType = dateload['Type']
if ComicYear is None: ComicYear = SeriesYear
if dateload['Volume'] is None:
logger.info('Marking %s #%s as wanted...' % (ComicName, ComicIssue))
else:
logger.info('Marking %s (%s) #%s as wanted...' % (ComicName, dateload['Volume'], ComicIssue))
logger.fdebug('publisher: %s' % Publisher)
controlValueDict = {"IssueArcID": IssueArcID}
newStatus = {"Status": "Wanted"}
myDB.upsert("storyarcs", newStatus, controlValueDict)
moduletype = '[STORY-ARCS]'
passinfo = {'issueid': IssueArcID,
'comicname': ComicName,
'seriesyear': SeriesYear,
'comicid': ComicID,
'issuenumber': ComicIssue,
'booktype': BookType}
elif mode == 'pullwant': #and ComicID is None
#this is for marking individual comics from the pullist to be downloaded.
#--comicid & issueid may both be known (or either) at any given point if alt_pull = 2
#because ComicID and IssueID will both be None due to pullist, it's probably
#better to set both to some generic #, and then filter out later...
IssueDate = pullinfo
try:
SeriesYear = IssueDate[:4]
except:
SeriesYear == now.year
if Publisher == 'COMICS': Publisher = None
moduletype = '[PULL-LIST]'
passinfo = {'issueid': IssueID,
'comicname': ComicName,
'seriesyear': SeriesYear,
'comicid': ComicID,
'issuenumber': ComicIssue,
'booktype': BookType}
elif mode == 'want' or mode == 'want_ann' or manualsearch:
cdname = myDB.selectone("SELECT * from comics where ComicID=?", [ComicID]).fetchone()
ComicName_Filesafe = cdname['ComicName_Filesafe']
SeriesYear = cdname['ComicYear']
AlternateSearch = cdname['AlternateSearch']
Publisher = cdname['ComicPublisher']
UseAFuzzy = cdname['UseFuzzy']
AllowPacks= cdname['AllowPacks']
ComicVersion = cdname['ComicVersion']
ComicName = cdname['ComicName']
TorrentID_32p = cdname['TorrentID_32P']
BookType = cdname['Type']
controlValueDict = {"IssueID": IssueID}
newStatus = {"Status": "Wanted"}
if mode == 'want':
if manualsearch:
logger.info('Initiating manual search for %s issue: %s' % (ComicName, ComicIssue))
else:
logger.info('Marking %s issue: %s as wanted...' % (ComicName, ComicIssue))
myDB.upsert("issues", newStatus, controlValueDict)
else:
annual_name = myDB.selectone("SELECT * FROM annuals WHERE ComicID=? and IssueID=?", [ComicID, IssueID]).fetchone()
if annual_name is None:
logger.fdebug('Unable to locate.')
else:
ComicName = annual_name['ReleaseComicName']
if manualsearch:
logger.info('Initiating manual search for %s : %s' % (ComicName, ComicIssue))
else:
logger.info('Marking %s : %s as wanted...' % (ComicName, ComicIssue))
myDB.upsert("annuals", newStatus, controlValueDict)
moduletype = '[WANTED-SEARCH]'
passinfo = {'issueid': IssueID,
'comicname': ComicName,
'seriesyear': SeriesYear,
'comicid': ComicID,
'issuenumber': ComicIssue,
'booktype': BookType}
if mode == 'want':
issues = myDB.selectone("SELECT IssueDate, ReleaseDate FROM issues WHERE IssueID=?", [IssueID]).fetchone()
elif mode == 'want_ann':
issues = myDB.selectone("SELECT IssueDate, ReleaseDate FROM annuals WHERE IssueID=?", [IssueID]).fetchone()
if ComicYear == None:
ComicYear = str(issues['IssueDate'])[:4]
if issues['ReleaseDate'] is None or issues['ReleaseDate'] == '0000-00-00':
logger.info('No Store Date found for given issue. This is probably due to not Refreshing the Series beforehand.')
logger.info('I Will assume IssueDate as Store Date, but you should probably Refresh the Series and try again if required.')
storedate = issues['IssueDate']
else:
storedate = issues['ReleaseDate']
if BookType == 'TPB':
logger.info('%s[%s] Now Queueing %s (%s) for search' % (moduletype, BookType, ComicName, SeriesYear))
elif ComicIssue is None:
logger.info('%s Now Queueing %s (%s) for search' % (moduletype, ComicName, SeriesYear))
else:
logger.info('%s Now Queueing %s (%s) #%s for search' % (moduletype, ComicName, SeriesYear, ComicIssue))
#s = mylar.SEARCH_QUEUE.put({'issueid': IssueID, 'comicname': ComicName, 'seriesyear': SeriesYear, 'comicid': ComicID, 'issuenumber': ComicIssue, 'booktype': BookType})
s = mylar.SEARCH_QUEUE.put(passinfo)
if manualsearch:
# if it's a manual search, return to null here so the thread will die and not cause http redirect errors.
return
if ComicID:
return cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % ComicID)
else:
return
#raise cherrypy.HTTPRedirect(redirect)
queueissue.exposed = True
def unqueueissue(self, IssueID, ComicID, ComicName=None, Issue=None, FutureID=None, mode=None, ReleaseComicID=None):
myDB = db.DBConnection()
if ComicName is None:
if ReleaseComicID is None: #ReleaseComicID is used for annuals.
issue = myDB.selectone('SELECT * FROM issues WHERE IssueID=?', [IssueID]).fetchone()
else:
issue = None
annchk = 'no'
if issue is None:
if mylar.CONFIG.ANNUALS_ON:
if ReleaseComicID is None:
issann = myDB.selectone('SELECT * FROM annuals WHERE IssueID=?', [IssueID]).fetchone()
else:
issann = myDB.selectone('SELECT * FROM annuals WHERE IssueID=? AND ReleaseComicID=?', [IssueID, ReleaseComicID]).fetchone()
ComicName = issann['ReleaseComicName']
IssueNumber = issann['Issue_Number']
annchk = 'yes'
ComicID = issann['ComicID']
ReleaseComicID = issann['ReleaseComicID']
else:
ComicName = issue['ComicName']
IssueNumber = issue['Issue_Number']
controlValueDict = {"IssueID": IssueID}
if mode == 'failed' and mylar.CONFIG.FAILED_DOWNLOAD_HANDLING:
logger.info(u"Marking " + ComicName + " issue # " + IssueNumber + " as Failed...")
newValueDict = {"Status": "Failed"}
myDB.upsert("failed", newValueDict, controlValueDict)
if annchk == 'yes':
myDB.upsert("annuals", newValueDict, controlValueDict)
else:
myDB.upsert("issues", newValueDict, controlValueDict)
self.failed_handling(ComicID=ComicID, IssueID=IssueID)
else:
logger.info(u"Marking " + ComicName + " issue # " + IssueNumber + " as Skipped...")
newValueDict = {"Status": "Skipped"}
if annchk == 'yes':
myDB.upsert("annuals", newValueDict, controlValueDict)
else:
myDB.upsert("issues", newValueDict, controlValueDict)
else:
#if ComicName is not None, then it's from the FuturePull list that we're 'unwanting' an issue.
#ComicID may be present if it's a watch from the Watchlist, otherwise it won't exist.
if ComicID is not None and ComicID != 'None':
logger.info('comicid present:' + str(ComicID))
thefuture = myDB.selectone('SELECT * FROM future WHERE ComicID=?', [ComicID]).fetchone()
else:
logger.info('FutureID: ' + str(FutureID))
logger.info('no comicid - ComicName: ' + str(ComicName) + ' -- Issue: #' + Issue)
thefuture = myDB.selectone('SELECT * FROM future WHERE FutureID=?', [FutureID]).fetchone()
if thefuture is None:
logger.info('Cannot find the corresponding issue in the Futures List for some reason. This is probably an Error.')
else:
logger.info('Marking ' + thefuture['COMIC'] + ' issue # ' + thefuture['ISSUE'] + ' as skipped...')
if ComicID is not None and ComicID != 'None':
cVDict = {"ComicID": thefuture['ComicID']}
else:
cVDict = {"FutureID": thefuture['FutureID']}
nVDict = {"Status": "Skipped"}
logger.info('cVDict:' + str(cVDict))
logger.info('nVDict:' + str(nVDict))
myDB.upsert("future", nVDict, cVDict)
unqueueissue.exposed = True
def failed_handling(self, ComicID, IssueID):
import Queue
queue = Queue.Queue()
FailProcess = Failed.FailedProcessor(issueid=IssueID, comicid=ComicID, queue=queue)
thread_ = threading.Thread(target=FailProcess.Process, name="FAILED Post-Processing")
thread_.start()
thread_.join()
failchk = queue.get()
if failchk[0]['mode'] == 'retry':
logger.info('Attempting to return to search module with ' + str(failchk[0]['issueid']))
if failchk[0]['annchk'] == 'no': mode = 'want'
else: mode = 'want_ann'
self.queueit(mode=mode, ComicName=failchk[0]['comicname'], ComicIssue=failchk[0]['issuenumber'], ComicID=failchk[0]['comicid'], IssueID=failchk[0]['issueid'], manualsearch=True)
elif failchk[0]['mode'] == 'stop':
pass
else:
logger.error('mode is unsupported: ' + failchk[0]['mode'])
failed_handling.exposed = True
def archiveissue(self, IssueID, comicid):
myDB = db.DBConnection()
issue = myDB.selectone('SELECT * FROM issues WHERE IssueID=?', [IssueID]).fetchone()
annchk = 'no'
if issue is None:
if mylar.CONFIG.ANNUALS_ON:
issann = myDB.selectone('SELECT * FROM annuals WHERE IssueID=?', [IssueID]).fetchone()
comicname = issann['ReleaseComicName']
issue = issann['Issue_Number']
annchk = 'yes'
comicid = issann['ComicID']
else:
comicname = issue['ComicName']
issue = issue['Issue_Number']
logger.info(u"Marking " + comicname + " issue # " + str(issue) + " as archived...")
controlValueDict = {'IssueID': IssueID}
newValueDict = {'Status': 'Archived'}
if annchk == 'yes':
myDB.upsert("annuals", newValueDict, controlValueDict)
else:
myDB.upsert("issues", newValueDict, controlValueDict)
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % comicid)
archiveissue.exposed = True
def pullSearch(self, week, year):
myDB = db.DBConnection()
#retrieve a list of all the issues that are in a Wanted state from the pull that we can search for.
ps = myDB.select("SELECT * from weekly WHERE Status='Wanted' AND weeknumber=? AND year=?", [int(week), year])
if ps is None:
logger.info('No items are marked as Wanted on the pullist to be searched for at this time')
return
issuesToSearch = []
for p in ps:
if p['IssueID'] is not None:
issuesToSearch.append(p['IssueID'])
if len(issuesToSearch) > 0:
logger.info('Now force searching for ' + str(len(issuesToSearch)) + ' issues from the pullist for week ' + str(week))
threading.Thread(target=search.searchIssueIDList, args=[issuesToSearch]).start()
else:
logger.info('Issues are marked as Wanted, but no issue information is available yet so I cannot search for anything. Try Recreating the pullist if you think this is error.')
return
pullSearch.exposed = True
def pullist(self, week=None, year=None, generateonly=False, current=None):
myDB = db.DBConnection()
autowant = []
if generateonly is False:
autowants = myDB.select("SELECT * FROM futureupcoming WHERE Status='Wanted'")
if autowants:
for aw in autowants:
autowant.append({"ComicName": aw['ComicName'],
"IssueNumber": aw['IssueNumber'],
"Publisher": aw['Publisher'],
"Status": aw['Status'],
"DisplayComicName": aw['DisplayComicName']})
weeklyresults = []
wantedcount = 0
weekinfo = helpers.weekly_info(week, year, current)
popit = myDB.select("SELECT * FROM sqlite_master WHERE name='weekly' and type='table'")
if popit:
w_results = myDB.select("SELECT * from weekly WHERE weeknumber=? AND year=?", [int(weekinfo['weeknumber']),weekinfo['year']])
if len(w_results) == 0:
logger.info('trying to repopulate to week: ' + str(weekinfo['weeknumber']) + '-' + str(weekinfo['year']))
repoll = self.manualpull(weeknumber=weekinfo['weeknumber'],year=weekinfo['year'])
if repoll['status'] == 'success':
w_results = myDB.select("SELECT * from weekly WHERE weeknumber=? AND year=?", [int(weekinfo['weeknumber']),weekinfo['year']])
else:
logger.warn('Problem repopulating the pullist for week ' + str(weekinfo['weeknumber']) + ', ' + str(weekinfo['year']))
if mylar.CONFIG.ALT_PULL == 2:
logger.warn('Attempting to repoll against legacy pullist in order to have some kind of updated listing for the week.')
repoll = self.manualpull()
if repoll['status'] == 'success':
w_results = myDB.select("SELECT * from weekly WHERE weeknumber=? AND year=?", [int(weekinfo['weeknumber']),weekinfo['year']])
else:
logger.warn('Unable to populate the pull-list. Not continuing at this time (will try again in abit)')
if all([w_results is None, generateonly is False]):
return serve_template(templatename="weeklypull.html", title="Weekly Pull", weeklyresults=weeklyresults, pullfilter=True, weekfold=weekinfo['week_folder'], wantedcount=0, weekinfo=weekinfo)
watchlibrary = helpers.listLibrary()
issueLibrary = helpers.listIssues(weekinfo['weeknumber'], weekinfo['year'])
oneofflist = helpers.listoneoffs(weekinfo['weeknumber'], weekinfo['year'])
chklist = []
for weekly in w_results:
xfound = False
tmp_status = weekly['Status']
if weekly['ComicID'] in watchlibrary:
haveit = watchlibrary[weekly['ComicID']]['comicid']
if weekinfo['weeknumber']:
if watchlibrary[weekly['ComicID']]['status'] == 'Paused':
tmp_status = 'Paused'
elif any([week >= int(weekinfo['weeknumber']), week is None]) and all([mylar.CONFIG.AUTOWANT_UPCOMING, tmp_status == 'Skipped']):
tmp_status = 'Wanted'
for x in issueLibrary:
if weekly['IssueID'] == x['IssueID'] and tmp_status != 'Paused':
xfound = True
tmp_status = x['Status']
break
else:
xlist = [x['Status'] for x in oneofflist if x['IssueID'] == weekly['IssueID']]
if xlist:
haveit = 'OneOff'
tmp_status = xlist[0]
else:
haveit = "No"
linkit = None
if all([weekly['ComicID'] is not None, weekly['ComicID'] != '', haveit == 'No']) or haveit == 'OneOff':
linkit = 'http://comicvine.gamespot.com/volume/4050-' + str(weekly['ComicID'])
else:
#setting it here will force it to set the link to the right comicid regardless of annuals or not
linkit = haveit
x = None
try:
x = float(weekly['ISSUE'])
except ValueError, e:
if 'au' in weekly['ISSUE'].lower() or 'ai' in weekly['ISSUE'].lower() or '.inh' in weekly['ISSUE'].lower() or '.now' in weekly['ISSUE'].lower() or '.mu' in weekly['ISSUE'].lower() or '.hu' in weekly['ISSUE'].lower():
x = weekly['ISSUE']
if x is not None:
if not autowant:
weeklyresults.append({
"PUBLISHER": weekly['PUBLISHER'],
"ISSUE": weekly['ISSUE'],
"COMIC": weekly['COMIC'],
"STATUS": tmp_status,
"COMICID": weekly['ComicID'],
"ISSUEID": weekly['IssueID'],
"VOLUME": weekly['volume'],
"SERIESYEAR": weekly['seriesyear'],
"HAVEIT": haveit,
"LINK": linkit,
"HASH": None,
"AUTOWANT": False,
"FORMAT": weekly['format']
})
else:
if any(x['ComicName'].lower() == weekly['COMIC'].lower() for x in autowant):
weeklyresults.append({
"PUBLISHER": weekly['PUBLISHER'],
"ISSUE": weekly['ISSUE'],
"COMIC": weekly['COMIC'],
"STATUS": tmp_status,
"COMICID": weekly['ComicID'],
"ISSUEID": weekly['IssueID'],
"VOLUME": weekly['volume'],
"SERIESYEAR": weekly['seriesyear'],
"HAVEIT": haveit,
"LINK": linkit,
"HASH": None,
"AUTOWANT": True,
"FORMAT": weekly['format']
})
else:
weeklyresults.append({
"PUBLISHER": weekly['PUBLISHER'],
"ISSUE": weekly['ISSUE'],
"COMIC": weekly['COMIC'],
"STATUS": tmp_status,
"COMICID": weekly['ComicID'],
"ISSUEID": weekly['IssueID'],
"VOLUME": weekly['volume'],
"SERIESYEAR": weekly['seriesyear'],
"HAVEIT": haveit,
"LINK": linkit,
"HASH": None,
"AUTOWANT": False,
"FORMAT": weekly['format']
})
if tmp_status == 'Wanted':
wantedcount +=1
elif tmp_status == 'Snatched':
chklist.append(str(weekly['IssueID']))
weeklyresults = sorted(weeklyresults, key=itemgetter('PUBLISHER', 'COMIC'), reverse=False)
else:
self.manualpull()
if generateonly is True:
return weeklyresults, weekinfo
else:
endresults = []
if len(chklist) > 0:
for genlist in helpers.chunker(chklist, 200):
tmpsql = "SELECT * FROM snatched where Status='Snatched' and status != 'Post-Processed' and (provider='32P' or Provider='WWT' or Provider='DEM') AND IssueID in ({seq})".format(seq=','.join(['?'] *(len(genlist))))
chkthis = myDB.select(tmpsql, genlist)
if chkthis is None:
continue
else:
for w in weeklyresults:
weekit = w
snatchit = [x['hash'] for x in chkthis if w['ISSUEID'] == x['IssueID']]
try:
if snatchit:
logger.fdebug('[%s] Discovered previously snatched torrent not downloaded. Marking for manual auto-snatch retrieval: %s' % (w['COMIC'], ''.join(snatchit)))
weekit['HASH'] = ''.join(snatchit)
else:
weekit['HASH'] = None
except:
weekit['HASH'] = None
endresults.append(weekit)
weeklyresults = endresults
if week:
return serve_template(templatename="weeklypull.html", title="Weekly Pull", weeklyresults=weeklyresults, pullfilter=True, weekfold=weekinfo['week_folder'], wantedcount=wantedcount, weekinfo=weekinfo)
else:
return serve_template(templatename="weeklypull.html", title="Weekly Pull", weeklyresults=weeklyresults, pullfilter=True, weekfold=weekinfo['week_folder'], wantedcount=wantedcount, weekinfo=weekinfo)
pullist.exposed = True
def removeautowant(self, comicname, release):
myDB = db.DBConnection()
logger.fdebug('Removing ' + comicname + ' from the auto-want list.')
myDB.action("DELETE FROM futureupcoming WHERE ComicName=? AND IssueDate=? AND Status='Wanted'", [comicname, release])
removeautowant.exposed = True
def futurepull(self):
from mylar import solicit
#get month-year here, and self-populate in future
now = datetime.datetime.now()
if len(str(now.month)) != 2:
month = '0' + str(now.month)
else:
month = str(now.month)
year = str(now.year)
logger.fdebug('month = ' + str(month))
logger.fdebug('year = ' + str(year))
threading.Thread(target=solicit.solicit, args=[month, year]).start()
raise cherrypy.HTTPRedirect("futurepulllist")
futurepull.exposed = True
def futurepulllist(self):
myDB = db.DBConnection()
futureresults = []
watchresults = []
popthis = myDB.select("SELECT * FROM sqlite_master WHERE name='futureupcoming' and type='table'")
if popthis:
l_results = myDB.select("SELECT * FROM futureupcoming WHERE Status='Wanted'")
for lres in l_results:
watchresults.append({
"ComicName": lres['ComicName'],
"IssueNumber": lres['IssueNumber'],
"ComicID": lres['ComicID'],
"IssueDate": lres['IssueDate'],
"Publisher": lres['Publisher'],
"Status": lres['Status']
})
logger.fdebug('There are ' + str(len(watchresults)) + ' issues that you are watching for but are not on your watchlist yet.')
popit = myDB.select("SELECT * FROM sqlite_master WHERE name='future' and type='table'")
if popit:
f_results = myDB.select("SELECT SHIPDATE, PUBLISHER, ISSUE, COMIC, EXTRA, STATUS, ComicID, FutureID from future")
for future in f_results:
x = None
if future['ISSUE'] is None: break
try:
x = float(future['ISSUE'])
except ValueError, e:
if 'au' in future['ISSUE'].lower() or 'ai' in future['ISSUE'].lower() or '.inh' in future['ISSUE'].lower() or '.now' in future['ISSUE'].lower() or '.mu' in future['ISSUE'].lower() or '.hu' in future['ISSUE'].lower():
x = future['ISSUE']
if future['EXTRA'] == 'N/A' or future['EXTRA'] == '':
future_extra = ''
else:
future_extra = future['EXTRA']
if '(of' in future['EXTRA'].lower():
future_extra = re.sub('[\(\)]', '', future['EXTRA'])
if x is not None:
#here we check the status to make sure it's ok since we loaded all the Watch For earlier.
chkstatus = future['STATUS']
for wr in watchresults:
if wr['ComicName'] == future['COMIC'] and wr['IssueNumber'] == future['ISSUE']:
logger.info('matched on Name: ' + wr['ComicName'] + ' to ' + future['COMIC'])
logger.info('matched on Issue: #' + wr['IssueNumber'] + ' to #' + future['ISSUE'])
logger.info('matched on ID: ' + str(wr['ComicID']) + ' to ' + str(future['ComicID']))
chkstatus = wr['Status']
break
futureresults.append({
"SHIPDATE": future['SHIPDATE'],
"PUBLISHER": future['PUBLISHER'],
"ISSUE": future['ISSUE'],
"COMIC": future['COMIC'],
"EXTRA": future_extra,
"STATUS": chkstatus,
"COMICID": future['ComicID'],
"FUTUREID": future['FutureID']
})
futureresults = sorted(futureresults, key=itemgetter('SHIPDATE', 'PUBLISHER', 'COMIC'), reverse=False)
else:
logger.error('No results to post for upcoming issues...something is probably wrong')
return
return serve_template(templatename="futurepull.html", title="future Pull", futureresults=futureresults, pullfilter=True)
futurepulllist.exposed = True
def add2futurewatchlist(self, ComicName, Issue, Publisher, ShipDate, weeknumber, year, FutureID=None):
#ShipDate is just weekinfo['midweek'] #a tuple ('weeknumber','startweek','midweek','endweek','year')
myDB = db.DBConnection()
logger.info(ShipDate)
if FutureID is not None:
chkfuture = myDB.selectone('SELECT * FROM futureupcoming WHERE ComicName=? AND IssueNumber=? WHERE weeknumber=? AND year=?', [ComicName, Issue, weeknumber, year]).fetchone()
if chkfuture is not None:
logger.info('Already on Future Upcoming list - not adding at this time.')
return
logger.info('Adding ' + ComicName + ' # ' + str(Issue) + ' [' + Publisher + '] to future upcoming watchlist')
newCtrl = {"ComicName": ComicName,
"IssueNumber": Issue,
"Publisher": Publisher}
newVal = {"Status": "Wanted",
"IssueDate": ShipDate,
"weeknumber": weeknumber,
"year": year}
myDB.upsert("futureupcoming", newVal, newCtrl)
if FutureID is not None:
fCtrl = {"FutureID": FutureID}
fVal = {"Status": "Wanted"}
myDB.upsert("future", fVal, fCtrl)
add2futurewatchlist.exposed = True
def future_check(self):
weeklypull.future_check()
raise cherrypy.HTTPRedirect("upcoming")
future_check.exposed = True
def filterpull(self):
myDB = db.DBConnection()
weeklyresults = myDB.select("SELECT * from weekly")
pulldate = myDB.selectone("SELECT * from weekly").fetchone()
if pulldate is None:
raise cherrypy.HTTPRedirect("home")
return serve_template(templatename="weeklypull.html", title="Weekly Pull", weeklyresults=weeklyresults, pulldate=pulldate['SHIPDATE'], pullfilter=True)
filterpull.exposed = True
def manualpull(self,weeknumber=None,year=None):
logger.info('ALT_PULL: ' + str(mylar.CONFIG.ALT_PULL) + ' PULLBYFILE: ' + str(mylar.PULLBYFILE) + ' week: ' + str(weeknumber) + ' year: ' + str(year))
if all([mylar.CONFIG.ALT_PULL == 2, mylar.PULLBYFILE is False]) and weeknumber:
return mylar.locg.locg(weeknumber=weeknumber,year=year)
#raise cherrypy.HTTPRedirect("pullist?week=" + str(weeknumber) + "&year=" + str(year))
else:
weeklypull.pullit()
return {'status' : 'success'}
manualpull.exposed = True
def pullrecreate(self, weeknumber=None, year=None):
myDB = db.DBConnection()
forcecheck = 'yes'
if weeknumber is None:
myDB.action("DROP TABLE weekly")
mylar.dbcheck()
logger.info("Deleted existing pull-list data. Recreating Pull-list...")
else:
myDB.action('DELETE FROM weekly WHERE weeknumber=? and year=?', [int(weeknumber), int(year)])
logger.info("Deleted existing pull-list data for week %s, %s. Now Recreating the Pull-list..." % (weeknumber, year))
weeklypull.pullit(forcecheck, weeknumber, year)
weeklypull.future_check()
pullrecreate.exposed = True
def upcoming(self):
todaydate = datetime.datetime.today()
current_weeknumber = todaydate.strftime("%U")
#find the given week number for the current day
weeknumber = current_weeknumber
stweek = datetime.datetime.strptime(todaydate.strftime('%Y-%m-%d'), '%Y-%m-%d')
startweek = stweek - timedelta(days = (stweek.weekday() + 1) % 7)
midweek = startweek + timedelta(days = 3)
endweek = startweek + timedelta(days = 6)
weekyear = todaydate.strftime("%Y")
myDB = db.DBConnection()
#upcoming = myDB.select("SELECT * from issues WHERE ReleaseDate > date('now') order by ReleaseDate DESC")
#upcomingdata = myDB.select("SELECT * from upcoming WHERE IssueID is NULL AND IssueNumber is not NULL AND ComicName is not NULL order by IssueDate DESC")
#upcomingdata = myDB.select("SELECT * from upcoming WHERE IssueNumber is not NULL AND ComicName is not NULL order by IssueDate DESC")
upcomingdata = myDB.select("SELECT * from weekly WHERE Issue is not NULL AND Comic is not NULL order by weeknumber DESC")
if upcomingdata is None:
logger.info('No upcoming data as of yet...')
else:
futureupcoming = []
upcoming = []
upcoming_count = 0
futureupcoming_count = 0
#try:
# pull_date = myDB.selectone("SELECT SHIPDATE from weekly").fetchone()
# if (pull_date is None):
# pulldate = '00000000'
# else:
# pulldate = pull_date['SHIPDATE']
#except (sqlite3.OperationalError, TypeError), msg:
# logger.info(u"Error Retrieving weekly pull list - attempting to adjust")
# pulldate = '00000000'
for upc in upcomingdata:
# if len(upc['IssueDate']) <= 7:
# #if it's less than or equal 7, then it's a future-pull so let's check the date and display
# #tmpdate = datetime.datetime.com
# tmpdatethis = upc['IssueDate']
# if tmpdatethis[:2] == '20':
# tmpdate = tmpdatethis + '01' #in correct format of yyyymm
# else:
# findst = tmpdatethis.find('-') #find the '-'
# tmpdate = tmpdatethis[findst +1:] + tmpdatethis[:findst] + '01' #rebuild in format of yyyymm
# #timenow = datetime.datetime.now().strftime('%Y%m')
# else:
# #if it's greater than 7 it's a full date.
# tmpdate = re.sub("[^0-9]", "", upc['IssueDate']) #convert date to numerics only (should be in yyyymmdd)
# timenow = datetime.datetime.now().strftime('%Y%m%d') #convert to yyyymmdd
# #logger.fdebug('comparing pubdate of: ' + str(tmpdate) + ' to now date of: ' + str(timenow))
# pulldate = re.sub("[^0-9]", "", pulldate) #convert pulldate to numerics only (should be in yyyymmdd)
# if int(tmpdate) >= int(timenow) and int(tmpdate) == int(pulldate): #int(pulldate) <= int(timenow):
mylar.WANTED_TAB_OFF = False
try:
ab = int(upc['weeknumber'])
bc = int(upc['year'])
except TypeError:
logger.warn('Weekly Pull hasn\'t finished being generated as of yet (or has yet to initialize). Try to wait up to a minute to accomodate processing.')
mylar.WANTED_TAB_OFF = True
myDB.action("DROP TABLE weekly")
mylar.dbcheck()
logger.info("Deleted existed pull-list data. Recreating Pull-list...")
forcecheck = 'yes'
return threading.Thread(target=weeklypull.pullit, args=[forcecheck]).start()
if int(upc['weeknumber']) == int(weeknumber) and int(upc['year']) == int(weekyear):
if upc['Status'] == 'Wanted':
upcoming_count +=1
upcoming.append({"ComicName": upc['Comic'],
"IssueNumber": upc['Issue'],
"IssueDate": upc['ShipDate'],
"ComicID": upc['ComicID'],
"IssueID": upc['IssueID'],
"Status": upc['Status'],
"WeekNumber": upc['weeknumber'],
"DynamicName": upc['DynamicName']})
else:
if int(upc['weeknumber']) > int(weeknumber) and upc['Status'] == 'Wanted':
futureupcoming_count +=1
futureupcoming.append({"ComicName": upc['Comic'],
"IssueNumber": upc['Issue'],
"IssueDate": upc['ShipDate'],
"ComicID": upc['ComicID'],
"IssueID": upc['IssueID'],
"Status": upc['Status'],
"WeekNumber": upc['weeknumber'],
"DynamicName": upc['DynamicName']})
# elif int(tmpdate) >= int(timenow):
# if len(upc['IssueDate']) <= 7:
# issuedate = tmpdate[:4] + '-' + tmpdate[4:6] + '-00'
# else:
# issuedate = upc['IssueDate']
# if upc['Status'] == 'Wanted':
# futureupcoming_count +=1
# futureupcoming.append({"ComicName": upc['ComicName'],
# "IssueNumber": upc['IssueNumber'],
# "IssueDate": issuedate,
# "ComicID": upc['ComicID'],
# "IssueID": upc['IssueID'],
# "Status": upc['Status'],
# "DisplayComicName": upc['DisplayComicName']})
futureupcoming = sorted(futureupcoming, key=itemgetter('IssueDate', 'ComicName', 'IssueNumber'), reverse=True)
#fix None DateAdded points here
helpers.DateAddedFix()
issues = myDB.select("SELECT * from issues WHERE Status='Wanted'")
if mylar.CONFIG.UPCOMING_STORYARCS is True:
arcs = myDB.select("SELECT * from storyarcs WHERE Status='Wanted'")
else:
arcs = []
if mylar.CONFIG.UPCOMING_SNATCHED is True:
issues += myDB.select("SELECT * from issues WHERE Status='Snatched'")
if mylar.CONFIG.UPCOMING_STORYARCS is True:
arcs += myDB.select("SELECT * from storyarcs WHERE Status='Snatched'")
if mylar.CONFIG.FAILED_DOWNLOAD_HANDLING is True:
issues += myDB.select("SELECT * from issues WHERE Status='Failed'")
if mylar.CONFIG.UPCOMING_STORYARCS is True:
arcs += myDB.select("SELECT * from storyarcs WHERE Status='Failed'")
if mylar.CONFIG.UPCOMING_STORYARCS is True:
issues += arcs
isCounts = {}
isCounts[1] = 0 #1 wanted
isCounts[2] = 0 #2 snatched
isCounts[3] = 0 #3 failed
isCounts[4] = 0 #3 wantedTier
ann_list = []
ann_cnt = 0
if mylar.CONFIG.ANNUALS_ON:
#let's add the annuals to the wanted table so people can see them
#ComicName wasn't present in db initially - added on startup chk now.
annuals_list = myDB.select("SELECT * FROM annuals WHERE Status='Wanted'")
if mylar.CONFIG.UPCOMING_SNATCHED:
annuals_list += myDB.select("SELECT * FROM annuals WHERE Status='Snatched'")
if mylar.CONFIG.FAILED_DOWNLOAD_HANDLING:
annuals_list += myDB.select("SELECT * FROM annuals WHERE Status='Failed'")
# anncnt = myDB.select("SELECT COUNT(*) FROM annuals WHERE Status='Wanted' OR Status='Snatched'")
# ann_cnt = anncnt[0][0]
ann_list += annuals_list
issues += annuals_list
issues_tmp = sorted(issues, key=itemgetter('ReleaseDate'), reverse=True)
issues_tmp1 = sorted(issues_tmp, key=itemgetter('DateAdded'), reverse=True)
issues = sorted(issues_tmp1, key=itemgetter('Status'), reverse=True)
for curResult in issues:
baseissues = {'wanted': 1, 'snatched': 2, 'failed': 3}
for seas in baseissues:
if curResult['Status'] is None:
continue
else:
if seas in curResult['Status'].lower():
if all([curResult['DateAdded'] <= mylar.SEARCH_TIER_DATE, curResult['Status'] == 'Wanted']):
isCounts[4]+=1
else:
sconv = baseissues[seas]
isCounts[sconv]+=1
continue
isCounts = {"Wanted": str(isCounts[1]),
"Snatched": str(isCounts[2]),
"Failed": str(isCounts[3]),
"StoryArcs": str(len(arcs)),
"WantedTier": str(isCounts[4])}
iss_cnt = int(isCounts['Wanted'])
wantedcount = iss_cnt + int(isCounts['WantedTier']) # + ann_cnt
#let's straightload the series that have no issue data associated as of yet (ie. new series) from the futurepulllist
future_nodata_upcoming = myDB.select("SELECT * FROM futureupcoming WHERE IssueNumber='1' OR IssueNumber='0'")
#let's move any items from the upcoming table into the wanted table if the date has already passed.
#gather the list...
mvupcome = myDB.select("SELECT * from upcoming WHERE IssueDate < date('now') order by IssueDate DESC")
#get the issue ID's
for mvup in mvupcome:
myissue = myDB.selectone("SELECT ComicName, Issue_Number, IssueID, ComicID FROM issues WHERE IssueID=?", [mvup['IssueID']]).fetchone()
#myissue = myDB.action("SELECT * FROM issues WHERE Issue_Number=?", [mvup['IssueNumber']]).fetchone()
if myissue is None: pass
else:
logger.fdebug("--Updating Status of issues table because of Upcoming status--")
logger.fdebug("ComicName: " + str(myissue['ComicName']))
logger.fdebug("Issue number : " + str(myissue['Issue_Number']))
mvcontroldict = {"IssueID": myissue['IssueID']}
mvvalues = {"ComicID": myissue['ComicID'],
"Status": "Wanted"}
myDB.upsert("issues", mvvalues, mvcontroldict)
#remove old entry from upcoming so it won't try to continually download again.
logger.fdebug('[DELETE] - ' + mvup['ComicName'] + ' issue #: ' + str(mvup['IssueNumber']))
deleteit = myDB.action("DELETE from upcoming WHERE ComicName=? AND IssueNumber=?", [mvup['ComicName'], mvup['IssueNumber']])
return serve_template(templatename="upcoming.html", title="Upcoming", upcoming=upcoming, issues=issues, ann_list=ann_list, futureupcoming=futureupcoming, future_nodata_upcoming=future_nodata_upcoming, futureupcoming_count=futureupcoming_count, upcoming_count=upcoming_count, wantedcount=wantedcount, isCounts=isCounts)
upcoming.exposed = True
def skipped2wanted(self, comicid, fromupdate=None):
# change all issues for a given ComicID that are Skipped, into Wanted.
issuestowanted = []
issuesnumwant = []
myDB = db.DBConnection()
skipped2 = myDB.select("SELECT * from issues WHERE ComicID=? AND Status='Skipped'", [comicid])
for skippy in skipped2:
mvcontroldict = {"IssueID": skippy['IssueID']}
mvvalues = {"Status": "Wanted"}
myDB.upsert("issues", mvvalues, mvcontroldict)
issuestowanted.append(skippy['IssueID'])
issuesnumwant.append(skippy['Issue_Number'])
if len(issuestowanted) > 0:
if fromupdate is None:
logger.info("Marking issues: %s as Wanted" % issuesnumwant)
threading.Thread(target=search.searchIssueIDList, args=[issuestowanted]).start()
else:
logger.info('Marking issues: %s as Wanted' & issuesnumwant)
logger.info('These will be searched for on next Search Scan / Force Check')
return
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % [comicid])
skipped2wanted.exposed = True
def annualDelete(self, comicid, ReleaseComicID=None):
myDB = db.DBConnection()
if ReleaseComicID is None:
myDB.action("DELETE FROM annuals WHERE ComicID=?", [comicid])
logger.fdebug("Deleted all annuals from DB for ComicID of " + str(comicid))
else:
myDB.action("DELETE FROM annuals WHERE ReleaseComicID=?", [ReleaseComicID])
logger.fdebug("Deleted selected annual from DB with a ComicID of " + str(ReleaseComicID))
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % [comicid])
annualDelete.exposed = True
def ddl_requeue(self, mode, id=None):
myDB = db.DBConnection()
if id is None:
items = myDB.select("SELECT * FROM ddl_info WHERE status = 'Queued' ORDER BY updated_date DESC")
else:
oneitem = myDB.selectone("SELECT * FROM DDL_INFO WHERE ID=?", [id]).fetchone()
items = [oneitem]
itemlist = [x for x in items]
if itemlist is not None:
for item in itemlist:
if all([mylar.CONFIG.DDL_AUTORESUME is True, mode == 'resume', item['status'] != 'Completed']):
try:
filesize = os.stat(os.path.join(mylar.CONFIG.DDL_LOCATION, item['filename'])).st_size
except:
filesize = 0
resume = filesize
elif mode == 'abort':
myDB.upsert("ddl_info", {'Status': 'Failed'}, {'id': id}) #DELETE FROM ddl_info where ID=?', [id])
continue
elif mode == 'remove':
myDB.action('DELETE FROM ddl_info where ID=?', [id])
continue
else:
resume = None
mylar.DDL_QUEUE.put({'link': item['link'],
'mainlink': item['mainlink'],
'series': item['series'],
'year': item['year'],
'size': item['size'],
'comicid': item['comicid'],
'issueid': item['issueid'],
'id': item['id'],
'resume': resume})
linemessage = '%s successful for %s' % (mode, oneitem['series'])
if mode == 'restart_queue':
logger.info('[DDL-RESTART-QUEUE] DDL Queue successfully restarted. Put %s items back into the queue for downloading..' % len(itemlist))
linemessage = 'Successfully restarted Queue'
elif mode == 'restart':
logger.info('[DDL-RESTART] Successfully restarted %s [%s] for downloading..' % (oneitem['series'], oneitem['size']))
elif mode == 'requeue':
logger.info('[DDL-REQUEUE] Successfully requeued %s [%s] for downloading..' % (oneitem['series'], oneitem['size']))
elif mode == 'abort':
logger.info('[DDL-ABORT] Successfully aborted downloading of %s [%s]..' % (oneitem['series'], oneitem['size']))
elif mode == 'remove':
logger.info('[DDL-REMOVE] Successfully removed %s [%s]..' % (oneitem['series'], oneitem['size']))
return json.dumps({'status': True, 'message': linemessage})
ddl_requeue.exposed = True
def queueManage(self): # **args):
myDB = db.DBConnection()
resultlist = 'There are currently no items waiting in the Direct Download (DDL) Queue for processing.'
s_info = myDB.select("SELECT a.ComicName, a.ComicVersion, a.ComicID, a.ComicYear, b.Issue_Number, b.IssueID, c.size, c.status, c.id, c.updated_date, c.issues, c.year FROM comics as a INNER JOIN issues as b ON a.ComicID = b.ComicID INNER JOIN ddl_info as c ON b.IssueID = c.IssueID") # WHERE c.status != 'Downloading'")
o_info = myDB.select("Select a.ComicName, b.Issue_Number, a.IssueID, a.ComicID, c.size, c.status, c.id, c.updated_date, c.issues, c.year from oneoffhistory a join snatched b on a.issueid=b.issueid join ddl_info c on b.issueid=c.issueid where b.provider = 'ddl'")
if s_info:
resultlist = []
for si in s_info:
if si['issues'] is None:
issue = si['Issue_Number']
year = si['ComicYear']
if issue is not None:
issue = '#%s' % issue
else:
year = si['year']
issue = '#%s' % si['issues']
if si['status'] == 'Completed':
si_status = '100%'
else:
si_status = ''
resultlist.append({'series': si['ComicName'],
'issue': issue,
'id': si['id'],
'volume': si['ComicVersion'],
'year': year,
'size': si['size'].strip(),
'comicid': si['ComicID'],
'issueid': si['IssueID'],
'status': si['status'],
'updated_date': si['updated_date'],
'progress': si_status})
if o_info:
if type(resultlist) is str:
resultlist = []
for oi in o_info:
if oi['issues'] is None:
issue = oi['Issue_Number']
year = oi['year']
if issue is not None:
issue = '#%s' % issue
else:
year = oi['year']
issue = '#%s' % oi['issues']
if oi['status'] == 'Completed':
oi_status = '100%'
else:
oi_status = ''
resultlist.append({'series': oi['ComicName'],
'issue': issue,
'id': oi['id'],
'volume': None,
'year': year,
'size': oi['size'].strip(),
'comicid': oi['ComicID'],
'issueid': oi['IssueID'],
'status': oi['status'],
'updated_date': oi['updated_date'],
'progress': oi_status})
return serve_template(templatename="queue_management.html", title="Queue Management", resultlist=resultlist) #activelist=activelist, resultlist=resultlist)
queueManage.exposed = True
def queueManageIt(self, iDisplayStart=0, iDisplayLength=100, iSortCol_0=0, sSortDir_0="desc", sSearch="", **kwargs):
iDisplayStart = int(iDisplayStart)
iDisplayLength = int(iDisplayLength)
filtered = []
myDB = db.DBConnection()
resultlist = 'There are currently no items waiting in the Direct Download (DDL) Queue for processing.'
s_info = myDB.select("SELECT a.ComicName, a.ComicVersion, a.ComicID, a.ComicYear, b.Issue_Number, b.IssueID, c.size, c.status, c.id, c.updated_date, c.issues, c.year FROM comics as a INNER JOIN issues as b ON a.ComicID = b.ComicID INNER JOIN ddl_info as c ON b.IssueID = c.IssueID") # WHERE c.status != 'Downloading'")
o_info = myDB.select("Select a.ComicName, b.Issue_Number, a.IssueID, a.ComicID, c.size, c.status, c.id, c.updated_date, c.issues, c.year from oneoffhistory a join snatched b on a.issueid=b.issueid join ddl_info c on b.issueid=c.issueid where b.provider = 'ddl'")
if s_info:
resultlist = []
for si in s_info:
if si['issues'] is None:
issue = si['Issue_Number']
year = si['ComicYear']
if issue is not None:
issue = '#%s' % issue
else:
year = si['year']
issue = '#%s' % si['issues']
if si['status'] == 'Completed':
si_status = '100%'
else:
si_status = ''
if issue is not None:
if si['ComicVersion'] is not None:
series = '%s %s %s (%s)' % (si['ComicName'], si['ComicVersion'], issue, year)
else:
series = '%s %s (%s)' % (si['ComicName'], issue, year)
else:
if si['ComicVersion'] is not None:
series = '%s %s (%s)' % (si['ComicName'], si['ComicVersion'], year)
else:
series = '%s (%s)' % (si['ComicName'], year)
resultlist.append({'series': series, #i['ComicName'],
'issue': issue,
'queueid': si['id'],
'volume': si['ComicVersion'],
'year': year,
'size': si['size'].strip(),
'comicid': si['ComicID'],
'issueid': si['IssueID'],
'status': si['status'],
'updated_date': si['updated_date'],
'progress': si_status})
if o_info:
if type(resultlist) is str:
resultlist = []
for oi in o_info:
if oi['issues'] is None:
issue = oi['Issue_Number']
year = oi['year']
if issue is not None:
issue = '#%s' % issue
else:
year = oi['year']
issue = '#%s' % oi['issues']
if oi['status'] == 'Completed':
oi_status = '100%'
else:
oi_status = ''
if issue is not None:
series = '%s %s (%s)' % (oi['ComicName'], issue, year)
else:
series = '%s (%s)' % (oi['ComicName'], year)
resultlist.append({'series': series,
'issue': issue,
'queueid': oi['id'],
'volume': None,
'year': year,
'size': oi['size'].strip(),
'comicid': oi['ComicID'],
'issueid': oi['IssueID'],
'status': oi['status'],
'updated_date': oi['updated_date'],
'progress': oi_status})
if sSearch == "" or sSearch == None:
filtered = resultlist[::]
else:
filtered = [row for row in resultlist if any([sSearch.lower() in row['series'].lower(), sSearch.lower() in row['status'].lower()])]
sortcolumn = 'series'
if iSortCol_0 == '1':
sortcolumn = 'series'
elif iSortCol_0 == '2':
sortcolumn = 'size'
elif iSortCol_0 == '3':
sortcolumn = 'progress'
elif iSortCol_0 == '4':
sortcolumn = 'status'
elif iSortCol_0 == '5':
sortcolumn = 'updated_date'
filtered.sort(key=lambda x: x[sortcolumn], reverse=sSortDir_0 == "desc")
rows = filtered[iDisplayStart:(iDisplayStart + iDisplayLength)]
rows = [[row['comicid'], row['series'], row['size'], row['progress'], row['status'], row['updated_date'], row['queueid']] for row in rows]
#rows = [{'comicid': row['comicid'], 'series': row['series'], 'size': row['size'], 'progress': row['progress'], 'status': row['status'], 'updated_date': row['updated_date']} for row in rows]
#logger.info('rows: %s' % rows)
return json.dumps({
'iTotalDisplayRecords': len(filtered),
'iTotalRecords': len(resultlist),
'aaData': rows,
})
queueManageIt.exposed = True
def previewRename(self, **args): #comicid=None, comicidlist=None):
file_format = mylar.CONFIG.FILE_FORMAT
myDB = db.DBConnection()
resultlist = []
for k,v in args.items():
if any([k == 'x', k == 'y']):
continue
elif 'file_format' in k:
file_format = str(v)
elif 'comicid' in k:
if type(v) is list:
comicid = str(' '.join(v))
elif type(v) is unicode:
comicid = re.sub('[\]\[\']', '', v.decode('utf-8').encode('ascii')).strip()
else:
comicid = v
if comicid is not None and type(comicid) is not list:
comicidlist = []
comicidlist.append(comicid)
for cid in comicidlist:
comic = myDB.selectone("SELECT * FROM comics WHERE ComicID=?", [cid]).fetchone()
comicdir = comic['ComicLocation']
comicname = comic['ComicName']
issuelist = myDB.select("SELECT * FROM issues WHERE ComicID=? AND Location is not NULL ORDER BY ReleaseDate", [str(cid)])
if issuelist:
for issue in issuelist:
if 'annual' in issue['Location'].lower():
annualize = 'yes'
else:
annualize = None
import filers
rniss = filers.FileHandlers(ComicID=str(cid), IssueID=issue['IssueID'])
renameiss = rniss.rename_file(issue['Location'], annualize=annualize, file_format=file_format)
#renameiss = helpers.rename_param(comicid, comicname, issue['Issue_Number'], issue['Location'], comicyear=None, issueid=issue['IssueID'], annualize=annualize)
resultlist.append({'issueid': renameiss['issueid'],
'comicid': renameiss['comicid'],
'original': issue['Location'],
'new': renameiss['nfilename']})
logger.info('resultlist: %s' % resultlist)
return serve_template(templatename="previewrename.html", title="Preview Renamer", resultlist=resultlist, file_format=file_format, comicid=comicidlist)
previewRename.exposed = True
def manualRename(self, comicid):
if mylar.CONFIG.FILE_FORMAT == '':
logger.error("You haven't specified a File Format in Configuration/Advanced")
logger.error("Cannot rename files.")
return
if type(comicid) is not unicode:
comiclist = comicid
else:
comiclist = []
comiclist.append(comicid)
myDB = db.DBConnection()
for cid in comiclist:
filefind = 0
comic = myDB.selectone("SELECT * FROM comics WHERE ComicID=?", [cid]).fetchone()
comicdir = comic['ComicLocation']
comicname = comic['ComicName']
comicyear = comic['ComicYear']
extensions = ('.cbr', '.cbz', '.cb7')
issues = myDB.select("SELECT * FROM issues WHERE ComicID=?", [cid])
if mylar.CONFIG.ANNUALS_ON:
issues += myDB.select("SELECT * FROM annuals WHERE ComicID=?", [cid])
try:
if mylar.CONFIG.MULTIPLE_DEST_DIRS is not None and mylar.CONFIG.MULTIPLE_DEST_DIRS != 'None' and os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(comicdir)) != comicdir:
logger.fdebug('multiple_dest_dirs:' + mylar.CONFIG.MULTIPLE_DEST_DIRS)
logger.fdebug('dir: ' + comicdir)
logger.fdebug('os.path.basename: ' + os.path.basename(comicdir))
pathdir = os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(comicdir))
except:
pass
for root, dirnames, filenames in os.walk(comicdir):
for filename in filenames:
if filename.lower().endswith(extensions):
#logger.info("filename being checked is : " + str(filename))
for issue in issues:
if issue['Location'] == filename:
#logger.error("matched " + str(filename) + " to DB file " + str(issue['Location']))
if 'annual' in issue['Location'].lower():
annualize = 'yes'
else:
annualize = None
renameiss = helpers.rename_param(cid, comicname, issue['Issue_Number'], filename, comicyear=comicyear, issueid=issue['IssueID'], annualize=annualize)
nfilename = renameiss['nfilename']
srciss = os.path.join(comicdir, filename)
if filename != nfilename:
logger.info('Renaming ' + filename + ' ... to ... ' + renameiss['nfilename'])
try:
shutil.move(srciss, renameiss['destination_dir'])
except (OSError, IOError):
logger.error('Failed to move files - check directories and manually re-run.')
return
filefind+=1
else:
logger.info('Not renaming ' + filename + ' as it is in desired format already.')
#continue
logger.info('I have renamed ' + str(filefind) + ' issues of ' + comicname)
updater.forceRescan(cid)
if len(comiclist) > 1:
logger.info('[RENAMER] %s series have been renamed.' % len(comiclist))
manualRename.exposed = True
def searchScan(self, name):
return serve_template(templatename="searchfix.html", title="Manage", name=name)
searchScan.exposed = True
def manage(self):
mylarRoot = mylar.CONFIG.DESTINATION_DIR
import db
myDB = db.DBConnection()
jobresults = myDB.select('SELECT DISTINCT * FROM jobhistory')
if jobresults is not None:
tmp = []
for jb in jobresults:
if jb['prev_run_datetime'] is not None:
try:
pr = (datetime.datetime.strptime(jb['prev_run_datetime'][:19], '%Y-%m-%d %H:%M:%S') - datetime.datetime.utcfromtimestamp(0)).total_seconds()
except ValueError:
pr = (datetime.datetime.strptime(jb['prev_run_datetime'], '%Y-%m-%d %H:%M:%S.%f') - datetime.datetime.utcfromtimestamp(0)).total_seconds()
prev_run = datetime.datetime.fromtimestamp(pr)
else:
prev_run = None
if jb['next_run_datetime'] is not None:
try:
nr = (datetime.datetime.strptime(jb['next_run_datetime'][:19], '%Y-%m-%d %H:%M:%S') - datetime.datetime.utcfromtimestamp(0)).total_seconds()
except ValueError:
nr = (datetime.datetime.strptime(jb['next_run_datetime'], '%Y-%m-%d %H:%M:%S.%f') - datetime.datetime.utcfromtimestamp(0)).total_seconds()
next_run = datetime.datetime.fromtimestamp(nr)
else:
next_run = None
if 'rss' in jb['JobName'].lower():
if jb['Status'] == 'Waiting' and mylar.CONFIG.ENABLE_RSS is False:
mylar.RSS_STATUS = 'Paused'
elif jb['Status'] == 'Paused' and mylar.CONFIG.ENABLE_RSS is True:
mylar.RSS_STATUS = 'Waiting'
status = mylar.RSS_STATUS
interval = str(mylar.CONFIG.RSS_CHECKINTERVAL) + ' mins'
if 'weekly' in jb['JobName'].lower():
status = mylar.WEEKLY_STATUS
if mylar.CONFIG.ALT_PULL == 2: interval = '4 hrs'
else: interval = '24 hrs'
if 'search' in jb['JobName'].lower():
status = mylar.SEARCH_STATUS
interval = str(mylar.CONFIG.SEARCH_INTERVAL) + ' mins'
if 'updater' in jb['JobName'].lower():
status = mylar.UPDATER_STATUS
interval = str(int(mylar.DBUPDATE_INTERVAL)) + ' mins'
if 'folder' in jb['JobName'].lower():
status = mylar.MONITOR_STATUS
interval = str(mylar.CONFIG.DOWNLOAD_SCAN_INTERVAL) + ' mins'
if 'version' in jb['JobName'].lower():
status = mylar.VERSION_STATUS
interval = str(mylar.CONFIG.CHECK_GITHUB_INTERVAL) + ' mins'
if status != jb['Status'] and not('rss' in jb['JobName'].lower()):
status = jb['Status']
tmp.append({'prev_run_datetime': prev_run,
'next_run_datetime': next_run,
'interval': interval,
'jobname': jb['JobName'],
'status': status})
jobresults = tmp
return serve_template(templatename="manage.html", title="Manage", mylarRoot=mylarRoot, jobs=jobresults)
manage.exposed = True
def jobmanage(self, job, mode):
logger.info('%s : %s' % (job, mode))
jobid = None
job_id_map = {'DB Updater': 'dbupdater', 'Auto-Search': 'search', 'RSS Feeds': 'rss', 'Weekly Pullist': 'weekly', 'Check Version': 'version', 'Folder Monitor': 'monitor'}
for k,v in job_id_map.iteritems():
if k == job:
jobid = v
break
logger.info('jobid: %s' % jobid)
if jobid is not None:
myDB = db.DBConnection()
if mode == 'pause':
try:
mylar.SCHED.pause_job(jobid)
except:
pass
logger.info('[%s] Paused scheduled runtime.' % job)
ctrl = {'JobName': job}
val = {'Status': 'Paused'}
if jobid == 'rss':
mylar.CONFIG.ENABLE_RSS = False
elif jobid == 'monitor':
mylar.CONFIG.ENABLE_CHECK_FOLDER = False
myDB.upsert('jobhistory', val, ctrl)
elif mode == 'resume':
try:
mylar.SCHED.resume_job(jobid)
except:
pass
logger.info('[%s] Resumed scheduled runtime.' % job)
ctrl = {'JobName': job}
val = {'Status': 'Waiting'}
myDB.upsert('jobhistory', val, ctrl)
if jobid == 'rss':
mylar.CONFIG.ENABLE_RSS = True
elif jobid == 'monitor':
mylar.CONFIG.ENABLE_CHECK_FOLDER = True
helpers.job_management()
else:
logger.warn('%s cannot be matched against any scheduled jobs - maybe you should restart?' % job)
jobmanage.exposed = True
def schedulerForceCheck(self, jobid):
from apscheduler.triggers.date import DateTrigger
for jb in mylar.SCHED.get_jobs():
if jobid.lower() in str(jb).lower():
logger.info('[%s] Now force submitting job for jobid %s' % (jb, jobid))
if any([jobid == 'rss', jobid == 'weekly', jobid =='search', jobid == 'version', jobid == 'updater', jobid == 'monitor']):
jb.modify(next_run_time=datetime.datetime.utcnow())
break
schedulerForceCheck.exposed = True
def manageComics(self):
comics = helpers.havetotals()
return serve_template(templatename="managecomics.html", title="Manage Comics", comics=comics)
manageComics.exposed = True
def manageIssues(self, **kwargs):
status = kwargs['status']
results = []
resultlist = []
myDB = db.DBConnection()
if mylar.CONFIG.ANNUALS_ON:
issues = myDB.select("SELECT * from issues WHERE Status=? AND ComicName NOT LIKE '%Annual%'", [status])
annuals = myDB.select("SELECT * from annuals WHERE Status=?", [status])
else:
issues = myDB.select("SELECT * from issues WHERE Status=?", [status])
annuals = []
for iss in issues:
results.append(iss)
if status == 'Snatched':
resultlist.append(str(iss['IssueID']))
for ann in annuals:
results.append(ann)
if status == 'Snatched':
resultlist.append(str(ann['IssueID']))
endresults = []
if status == 'Snatched':
for genlist in helpers.chunker(resultlist, 200):
tmpsql = "SELECT * FROM snatched where Status='Snatched' and status != 'Post-Processed' and (provider='32P' or Provider='WWT' or Provider='DEM') AND IssueID in ({seq})".format(seq=','.join(['?'] *(len(genlist))))
chkthis = myDB.select(tmpsql, genlist)
if chkthis is None:
continue
else:
for r in results:
rr = dict(r)
snatchit = [x['hash'] for x in chkthis if r['ISSUEID'] == x['IssueID']]
try:
if snatchit:
logger.fdebug('[%s] Discovered previously snatched torrent not downloaded. Marking for manual auto-snatch retrieval: %s' % (r['ComicName'], ''.join(snatchit)))
rr['hash'] = ''.join(snatchit)
else:
rr['hash'] = None
except:
rr['hash'] = None
endresults.append(rr)
results = endresults
return serve_template(templatename="manageissues.html", title="Manage " + str(status) + " Issues", issues=results, status=status)
manageIssues.exposed = True
def manageFailed(self):
results = []
myDB = db.DBConnection()
failedlist = myDB.select('SELECT * from Failed')
for f in failedlist:
if f['Provider'] == 'Public Torrents':
link = helpers.torrent_create(f['Provider'], f['ID'])
else:
link = f['ID']
if f['DateFailed'] is None:
datefailed = '0000-00-0000'
else:
datefailed = f['DateFailed']
results.append({"Series": f['ComicName'],
"ComicID": f['ComicID'],
"Issue_Number": f['Issue_Number'],
"Provider": f['Provider'],
"Link": link,
"ID": f['ID'],
"FileName": f['NZBName'],
"DateFailed": datefailed})
return serve_template(templatename="managefailed.html", title="Failed DB Management", failed=results)
manageFailed.exposed = True
def flushImports(self):
myDB = db.DBConnection()
myDB.action('DELETE from importresults')
logger.info("Flushing all Import Results and clearing the tables")
flushImports.exposed = True
def markImports(self, action=None, **args):
import unicodedata
myDB = db.DBConnection()
comicstoimport = []
if action == 'massimport':
logger.info('Initiating mass import.')
cnames = myDB.select("SELECT ComicName, ComicID, Volume, DynamicName from importresults WHERE Status='Not Imported' GROUP BY DynamicName, Volume")
for cname in cnames:
if cname['ComicID']:
comicid = cname['ComicID']
else:
comicid = None
try:
comicstoimport.append({'ComicName': unicodedata.normalize('NFKD', cname['ComicName']).encode('utf-8', 'ignore').decode('utf-8', 'ignore'),
'DynamicName': cname['DynamicName'],
'Volume': cname['Volume'],
'ComicID': comicid})
except Exception as e:
logger.warn('[ERROR] There was a problem attempting to queue %s %s [%s] to import (ignoring): %s' % (cname['ComicName'],cname['Volume'],comicid, e))
logger.info(str(len(comicstoimport)) + ' series will be attempted to be imported.')
else:
if action == 'importselected':
logger.info('importing selected series.')
for k,v in args.items():
#k = Comicname[Volume]|ComicID
#v = DynamicName
Volst = k.find('[')
comicid_st = k.find('|')
if comicid_st == -1:
comicid = None
volume = re.sub('[\[\]]', '', k[Volst:]).strip()
else:
comicid = k[comicid_st+1:]
if comicid == 'None':
comicid = None
volume = re.sub('[\[\]]', '', k[Volst:comicid_st]).strip()
ComicName = k[:Volst].strip()
DynamicName = v
cid = ComicName.decode('utf-8', 'replace')
comicstoimport.append({'ComicName': cid,
'DynamicName': DynamicName,
'Volume': volume,
'ComicID': comicid})
elif action == 'removeimport':
for k,v in args.items():
Volst = k.find('[')
comicid_st = k.find('|')
if comicid_st == -1:
comicid = None
volume = re.sub('[\[\]]', '', k[Volst:]).strip()
else:
comicid = k[comicid_st+1:]
if comicid == 'None':
comicid = None
volume = re.sub('[\[\]]', '', k[Volst:comicid_st]).strip()
ComicName = k[:Volst].strip()
DynamicName = v
if volume is None or volume == 'None':
logger.info('Removing ' + ComicName + ' from the Import list')
myDB.action('DELETE from importresults WHERE DynamicName=? AND (Volume is NULL OR Volume="None")', [DynamicName])
else:
logger.info('Removing ' + ComicName + ' [' + str(volume) + '] from the Import list')
myDB.action('DELETE from importresults WHERE DynamicName=? AND Volume=?', [DynamicName, volume])
if len(comicstoimport) > 0:
logger.info('Initiating selected import mode for ' + str(len(comicstoimport)) + ' series.')
if len(comicstoimport) > 0:
logger.debug('The following series will now be attempted to be imported: %s' % comicstoimport)
threading.Thread(target=self.preSearchit, args=[None, comicstoimport, len(comicstoimport)]).start()
raise cherrypy.HTTPRedirect("importResults")
markImports.exposed = True
def markComics(self, action=None, **args):
myDB = db.DBConnection()
comicsToAdd = []
clist = []
for k,v in args.items():
if k == 'manage_comic_length':
continue
#k = Comicname[ComicYear]
#v = ComicID
comyr = k.find('[')
ComicYear = re.sub('[\[\]]', '', k[comyr:]).strip()
ComicName = k[:comyr].strip()
if isinstance(v, list):
#because multiple items can have the same comicname & year, we need to make sure they're all unique entries
for x in v:
clist.append({'ComicName': ComicName,
'ComicYear': ComicYear,
'ComicID': x})
else:
clist.append({'ComicName': ComicName,
'ComicYear': ComicYear,
'ComicID': v})
for cl in clist:
if action == 'delete':
logger.info('[MANAGE COMICS][DELETION] Now deleting ' + cl['ComicName'] + ' (' + str(cl['ComicYear']) + ') [' + str(cl['ComicID']) + '] form the DB.')
myDB.action('DELETE from comics WHERE ComicID=?', [cl['ComicID']])
myDB.action('DELETE from issues WHERE ComicID=?', [cl['ComicID']])
if mylar.CONFIG.ANNUALS_ON:
myDB.action('DELETE from annuals WHERE ComicID=?', [cl['ComicID']])
logger.info('[MANAGE COMICS][DELETION] Successfully deleted ' + cl['ComicName'] + '(' + str(cl['ComicYear']) + ')')
elif action == 'pause':
controlValueDict = {'ComicID': cl['ComicID']}
newValueDict = {'Status': 'Paused'}
myDB.upsert("comics", newValueDict, controlValueDict)
logger.info('[MANAGE COMICS][PAUSE] ' + cl['ComicName'] + ' has now been put into a Paused State.')
elif action == 'resume':
controlValueDict = {'ComicID': cl['ComicID']}
newValueDict = {'Status': 'Active'}
myDB.upsert("comics", newValueDict, controlValueDict)
logger.info('[MANAGE COMICS][RESUME] ' + cl['ComicName'] + ' has now been put into a Resumed State.')
elif action == 'recheck' or action == 'metatag':
comicsToAdd.append({'ComicID': cl['ComicID'],
'ComicName': cl['ComicName'],
'ComicYear': cl['ComicYear']})
else:
comicsToAdd.append(cl['ComicID'])
if len(comicsToAdd) > 0:
if action == 'recheck':
logger.info('[MANAGE COMICS][RECHECK-FILES] Rechecking Files for ' + str(len(comicsToAdd)) + ' series')
threading.Thread(target=self.forceRescan, args=[comicsToAdd,True,'recheck']).start()
elif action == 'metatag':
logger.info('[MANAGE COMICS][MASS METATAGGING] Now Metatagging Files for ' + str(len(comicsToAdd)) + ' series')
threading.Thread(target=self.forceRescan, args=[comicsToAdd,True,'metatag']).start()
elif action == 'rename':
logger.info('[MANAGE COMICS][MASS RENAMING] Now Renaming Files for ' + str(len(comicsToAdd)) + ' series')
threading.Thread(target=self.manualRename, args=[comicsToAdd]).start()
else:
logger.info('[MANAGE COMICS][REFRESH] Refreshing ' + str(len(comicsToAdd)) + ' series')
threading.Thread(target=updater.dbUpdate, args=[comicsToAdd]).start()
markComics.exposed = True
def forceUpdate(self):
from mylar import updater
threading.Thread(target=updater.dbUpdate).start()
raise cherrypy.HTTPRedirect("home")
forceUpdate.exposed = True
def forceSearch(self):
#from mylar import search
#threading.Thread(target=search.searchforissue).start()
#raise cherrypy.HTTPRedirect("home")
self.schedulerForceCheck(jobid='search')
forceSearch.exposed = True
def forceRescan(self, ComicID, bulk=False, action='recheck'):
if bulk:
cnt = 1
if action == 'recheck':
for cid in ComicID:
logger.info('[MASS BATCH][RECHECK-FILES][' + str(cnt) + '/' + str(len(ComicID)) + '] Rechecking ' + cid['ComicName'] + '(' + str(cid['ComicYear']) + ')')
updater.forceRescan(cid['ComicID'])
cnt+=1
logger.info('[MASS BATCH][RECHECK-FILES] I have completed rechecking files for ' + str(len(ComicID)) + ' series.')
else:
for cid in ComicID:
logger.info('[MASS BATCH][METATAGGING-FILES][' + str(cnt) + '/' + str(len(ComicID)) + '] Now Preparing to metatag series for ' + cid['ComicName'] + '(' + str(cid['ComicYear']) + ')')
self.group_metatag(ComicID=cid['ComicID'])
cnt+=1
logger.info('[MASS BATCH][METATAGGING-FILES] I have completed metatagging files for ' + str(len(ComicID)) + ' series.')
else:
threading.Thread(target=updater.forceRescan, args=[ComicID]).start()
forceRescan.exposed = True
def checkGithub(self):
from mylar import versioncheck
versioncheck.checkGithub()
raise cherrypy.HTTPRedirect("home")
checkGithub.exposed = True
def history(self):
myDB = db.DBConnection()
history = myDB.select('''SELECT * from snatched order by DateAdded DESC''')
return serve_template(templatename="history.html", title="History", history=history)
history.exposed = True
def reOrder(request):
return request
# return serve_template(templatename="reorder.html", title="ReoRdered!", reorder=request)
reOrder.exposed = True
def readlist(self):
myDB = db.DBConnection()
issuelist = myDB.select("SELECT * from readlist")
#tuple this
readlist = []
counts = []
c_added = 0 #count of issues that have been added to the readlist and remain in that status ( meaning not sent / read )
c_sent = 0 #count of issues that have been sent to a third-party device ( auto-marked after a successful send completion )
c_read = 0 #count of issues that have been marked as read ( manually marked as read - future: read state from xml )
for iss in issuelist:
if iss['Status'] == 'Added':
statuschange = iss['DateAdded']
c_added +=1
else:
if iss['Status'] == 'Read':
c_read +=1
elif iss['Status'] == 'Downloaded':
c_sent +=1
statuschange = iss['StatusChange']
readlist.append({"ComicID": iss['ComicID'],
"ComicName": iss['ComicName'],
"SeriesYear": iss['SeriesYear'],
"Issue_Number": iss['Issue_Number'],
"IssueDate": iss['IssueDate'],
"Status": iss['Status'],
"StatusChange": statuschange,
"inCacheDIR": iss['inCacheDIR'],
"Location": iss['Location'],
"IssueID": iss['IssueID']})
counts = {"added": c_added,
"read": c_read,
"sent": c_sent,
"total": (c_added + c_read + c_sent)}
return serve_template(templatename="readinglist.html", title="Reading Lists", issuelist=readlist, counts=counts)
readlist.exposed = True
def clear_arcstatus(self, issuearcid=None):
myDB = db.DBConnection()
myDB.upsert('storyarcs', {'Status': 'Skipped'}, {'IssueArcID': issuearcid})
logger.info('Status set to Skipped.')
clear_arcstatus.exposed = True
def storyarc_main(self, arcid=None):
myDB = db.DBConnection()
arclist = []
if arcid is None:
alist = myDB.select("SELECT * from storyarcs WHERE ComicName is not Null GROUP BY StoryArcID") #COLLATE NOCASE")
else:
alist = myDB.select("SELECT * from storyarcs WHERE ComicName is not Null AND StoryArcID=? GROUP BY StoryArcID", [arcid]) #COLLATE NOCASE")
for al in alist:
totalissues = myDB.select("SELECT COUNT(*) as count from storyarcs WHERE StoryARcID=? AND NOT Manual is 'deleted'", [al['StoryArcID']])
havecnt = myDB.select("SELECT COUNT(*) as count FROM storyarcs WHERE StoryArcID=? AND (Status='Downloaded' or Status='Archived')", [al['StoryArcID']])
havearc = havecnt[0][0]
totalarc = totalissues[0][0]
if not havearc:
havearc = 0
try:
percent = (havearc *100.0) /totalarc
if percent > 100:
percent = 101
except (ZeroDivisionError, TypeError):
percent = 0
totalarc = '?'
arclist.append({"StoryArcID": al['StoryArcID'],
"StoryArc": al['StoryArc'],
"TotalIssues": al['TotalIssues'],
"SeriesYear": al['SeriesYear'],
"StoryArcDir": al['StoryArc'],
"Status": al['Status'],
"percent": percent,
"Have": havearc,
"SpanYears": helpers.spantheyears(al['StoryArcID']),
"Total": totalarc,
"CV_ArcID": al['CV_ArcID']})
if arcid is None:
return serve_template(templatename="storyarc.html", title="Story Arcs", arclist=arclist, delete_type=0)
else:
return arclist[0]
storyarc_main.exposed = True
def detailStoryArc(self, StoryArcID, StoryArcName=None):
myDB = db.DBConnection()
arcinfo = myDB.select("SELECT * from storyarcs WHERE StoryArcID=? and NOT Manual IS 'deleted' order by ReadingOrder ASC", [StoryArcID])
try:
cvarcid = arcinfo[0]['CV_ArcID']
arcpub = arcinfo[0]['Publisher']
if StoryArcName is None:
StoryArcName = arcinfo[0]['StoryArc']
lowyear = 9999
maxyear = 0
issref = []
for la in arcinfo:
if all([la['Status'] == 'Downloaded', la['Location'] is None,]):
issref.append({'IssueID': la['IssueID'],
'ComicID': la['ComicID'],
'IssuePublisher': la['IssuePublisher'],
'Publisher': la['Publisher'],
'StoryArc': la['StoryArc'],
'StoryArcID': la['StoryArcID'],
'ComicName': la['ComicName'],
'IssueNumber': la['IssueNumber'],
'ReadingOrder': la['ReadingOrder']})
if la['IssueDate'] is None or la['IssueDate'] == '0000-00-00':
continue
else:
if int(la['IssueDate'][:4]) > maxyear:
maxyear = int(la['IssueDate'][:4])
if int(la['IssueDate'][:4]) < lowyear:
lowyear = int(la['IssueDate'][:4])
if maxyear == 0:
spanyears = la['SeriesYear']
elif lowyear == maxyear:
spanyears = str(maxyear)
else:
spanyears = '%s - %s' % (lowyear, maxyear)
sdir = helpers.arcformat(arcinfo[0]['StoryArc'], spanyears, arcpub)
except:
cvarcid = None
sdir = mylar.CONFIG.GRABBAG_DIR
if len(issref) > 0:
helpers.updatearc_locs(StoryArcID, issref)
arcinfo = myDB.select("SELECT * from storyarcs WHERE StoryArcID=? AND NOT Manual IS 'deleted' order by ReadingOrder ASC", [StoryArcID])
arcdetail = self.storyarc_main(arcid=arcinfo[0]['CV_ArcID'])
storyarcbanner = None
#bannerheight = 400
#bannerwidth = 263
filepath = None
sb = 'cache/storyarcs/' + str(arcinfo[0]['CV_ArcID']) + '-banner'
storyarc_imagepath = os.path.join(mylar.CONFIG.CACHE_DIR, 'storyarcs')
if not os.path.exists(storyarc_imagepath):
try:
os.mkdir(storyarc_imagepath)
except:
logger.warn('Unable to create storyarc image directory @ %s' % storyarc_imagepath)
if os.path.exists(storyarc_imagepath):
dir = os.listdir(storyarc_imagepath)
for fname in dir:
if str(arcinfo[0]['CV_ArcID']) in fname:
storyarcbanner = sb
filepath = os.path.join(storyarc_imagepath, fname)
# if any(['H' in fname, 'W' in fname]):
# if 'H' in fname:
# bannerheight = int(fname[fname.find('H')+1:fname.find('.')])
# elif 'W' in fname:
# bannerwidth = int(fname[fname.find('W')+1:fname.find('.')])
# if any([bannerwidth != 263, 'W' in fname]):
# #accomodate poster size
# storyarcbanner += 'W' + str(bannerheight)
# else:
# #for actual banner width (ie. 960x280)
# storyarcbanner += 'H' + str(bannerheight)
storyarcbanner += os.path.splitext(fname)[1] + '?' + datetime.datetime.now().strftime('%y-%m-%d %H:%M:%S')
break
template = 'storyarc_detail.html'
if filepath is not None:
import get_image_size
image = get_image_size.get_image_metadata(filepath)
imageinfo = json.loads(get_image_size.Image.to_str_json(image))
#logger.fdebug('imageinfo: %s' % imageinfo)
if imageinfo['width'] > imageinfo['height']:
template = 'storyarc_detail.html'
bannerheight = '280'
bannerwidth = '960'
else:
template = 'storyarc_detail.poster.html'
bannerwidth = '263'
bannerheight = '400'
else:
bannerheight = '280'
bannerwidth = '960'
return serve_template(templatename=template, title="Detailed Arc list", readlist=arcinfo, storyarcname=StoryArcName, storyarcid=StoryArcID, cvarcid=cvarcid, sdir=sdir, arcdetail=arcdetail, storyarcbanner=storyarcbanner, bannerheight=bannerheight, bannerwidth=bannerwidth, spanyears=spanyears)
detailStoryArc.exposed = True
def order_edit(self, id, value):
storyarcid = id[:id.find('.')]
issuearcid = id[id.find('.') +1:]
readingorder = value
#readingorder = value
valid_readingorder = None
#validate input here for reading order.
try:
if int(readingorder) >= 0:
valid_readingorder = int(readingorder)
if valid_readingorder == 0:
valid_readingorder = 1
except ValueError:
logger.error('Non-Numeric/Negative readingorder submitted. Rejecting due to sequencing error.')
return
if valid_readingorder is None:
logger.error('invalid readingorder supplied. Rejecting due to sequencing error')
return
myDB = db.DBConnection()
readchk = myDB.select("SELECT * FROM storyarcs WHERE StoryArcID=? AND NOT Manual is 'deleted' ORDER BY ReadingOrder", [storyarcid])
if readchk is None:
logger.error('Cannot edit this for some reason (Cannot locate Storyarc) - something is wrong.')
return
new_readorder = []
oldreading_seq = None
logger.fdebug('[%s] Issue to renumber sequence from : %s' % (issuearcid, valid_readingorder))
reading_seq = 1
for rc in sorted(readchk, key=itemgetter('ReadingOrder'), reverse=False):
filename = None
if rc['Location'] is not None:
filename = ntpath.basename(rc['Location'])
if str(issuearcid) == str(rc['IssueArcID']):
logger.fdebug('new order sequence detected at #: %s' % valid_readingorder)
if valid_readingorder > int(rc['ReadingOrder']):
oldreading_seq = int(rc['ReadingOrder'])
else:
oldreading_seq = int(rc['ReadingOrder']) + 1
reading_seq = valid_readingorder
issueid = rc['IssueID']
IssueArcID = issuearcid
elif int(rc['ReadingOrder']) < valid_readingorder:
logger.fdebug('keeping issue sequence of order #: %s' % rc['ReadingOrder'])
reading_seq = int(rc['ReadingOrder'])
issueid = rc['IssueID']
IssueArcID = rc['IssueArcID']
elif int(rc['ReadingOrder']) >= valid_readingorder:
if oldreading_seq is not None:
if valid_readingorder <= len(readchk):
reading_seq = int(rc['ReadingOrder'])
#reading_seq = oldreading_seq
else:
#valid_readingorder
if valid_readingorder < old_reading_seq:
reading_seq = int(rc['ReadingOrder'])
else:
reading_seq = oldreading_seq +1
logger.fdebug('old sequence discovered at %s to %s' % (oldreading_seq, reading_seq))
oldreading_seq = None
elif int(rc['ReadingOrder']) == valid_readingorder:
reading_seq = valid_readingorder +1
else:
reading_seq +=1 #valid_readingorder + (int(rc['ReadingOrder']) - valid_readingorder) +1
issueid = rc['IssueID']
IssueArcID = rc['IssueArcID']
logger.fdebug('reordering existing sequence as lower sequence has changed. Altering from %s to %s' % (rc['ReadingOrder'], reading_seq))
new_readorder.append({'IssueArcID': IssueArcID,
'IssueID': issueid,
'ReadingOrder': reading_seq,
'filename': filename})
#we resequence in the following way:
# everything before the new reading number stays the same
# everything after the new reading order gets incremented
# add in the new reading order at the desired sequence
# check for empty spaces (missing numbers in sequence) and fill them in.
logger.fdebug('new reading order: %s' % new_readorder)
#newrl = 0
for rl in sorted(new_readorder, key=itemgetter('ReadingOrder'), reverse=False):
if rl['filename'] is not None:
try:
if int(rl['ReadingOrder']) != int(rl['filename'][:rl['filename'].find('-')]) and mylar.CONFIG.READ2FILENAME is True:
logger.fdebug('Order-Change: %s TO %s' % (int(rl['filename'][:rl['filename'].find('-')]), int(rl['ReadingOrder'])))
logger.fdebug('%s to %s' % (rl['filename'], helpers.renamefile_readingorder(rl['ReadingOrder']) + '-' + rl['filename'][rl['filename'].find('-')+1:]))
except:
pass
rl_ctrl = {"IssueID": rl['IssueID'],
"IssueArcID": rl['IssueArcID'],
"StoryArcID": storyarcid}
r1_new = {"ReadingOrder": rl['ReadingOrder']}
myDB.upsert("storyarcs", r1_new, rl_ctrl)
logger.info('Updated Issue Date for issue #' + str(issuenumber))
return value
order_edit.exposed = True
def manual_arc_add(self, manual_issueid, manual_readingorder, storyarcid, x=None, y=None):
logger.fdebug('IssueID to be attached : ' + str(manual_issueid))
logger.fdebug('StoryArcID : ' + str(storyarcid))
logger.fdebug('Reading Order # : ' + str(manual_readingorder))
threading.Thread(target=helpers.manualArc, args=[manual_issueid, manual_readingorder, storyarcid]).start()
raise cherrypy.HTTPRedirect("detailStoryArc?StoryArcID=%s" % storyarcid)
manual_arc_add.exposed = True
def markreads(self, action=None, **args):
sendtablet_queue = []
myDB = db.DBConnection()
for IssueID in args:
if IssueID is None or 'issue_table' in IssueID or 'issue_table_length' in IssueID:
continue
else:
mi = myDB.selectone("SELECT * FROM readlist WHERE IssueID=?", [IssueID]).fetchone()
if mi is None:
continue
else:
comicname = mi['ComicName']
if action == 'Downloaded':
logger.fdebug(u"Marking %s #%s as %s" % (comicname, mi['Issue_Number'], action))
read = readinglist.Readinglist(IssueID)
read.addtoreadlist()
elif action == 'Read':
logger.fdebug(u"Marking %s #%s as %s" % (comicname, mi['Issue_Number'], action))
markasRead(IssueID)
elif action == 'Added':
logger.fdebug(u"Marking %s #%s as %s" % (comicname, mi['Issue_Number'], action))
read = readinglist.Readinglist(IssueID=IssueID)
read.addtoreadlist()
elif action == 'Remove':
logger.fdebug('Deleting %s #%s' % (comicname, mi['Issue_Number']))
myDB.action('DELETE from readlist WHERE IssueID=?', [IssueID])
elif action == 'Send':
logger.fdebug('Queuing ' + mi['Location'] + ' to send to tablet.')
sendtablet_queue.append({"filepath": mi['Location'],
"issueid": IssueID,
"comicid": mi['ComicID']})
if len(sendtablet_queue) > 0:
read = readinglist.Readinglist(sendtablet_queue)
threading.Thread(target=read.syncreading).start()
markreads.exposed = True
def removefromreadlist(self, IssueID=None, StoryArcID=None, IssueArcID=None, AllRead=None, ArcName=None, delete_type=None, manual=None):
myDB = db.DBConnection()
if IssueID:
myDB.action('DELETE from readlist WHERE IssueID=?', [IssueID])
logger.info("[DELETE-READ-ISSUE] Removed " + str(IssueID) + " from Reading List")
elif StoryArcID:
logger.info('[DELETE-ARC] Removing ' + ArcName + ' from your Story Arc Watchlist')
myDB.action('DELETE from storyarcs WHERE StoryArcID=?', [StoryArcID])
#ArcName should be an optional flag so that it doesn't remove arcs that have identical naming (ie. Secret Wars)
if delete_type:
if ArcName:
logger.info('[DELETE-STRAGGLERS-OPTION] Removing all traces of arcs with the name of : ' + ArcName)
myDB.action('DELETE from storyarcs WHERE StoryArc=?', [ArcName])
else:
logger.warn('[DELETE-STRAGGLERS-OPTION] No ArcName provided - just deleting by Story Arc ID')
stid = 'S' + str(StoryArcID) + '_%'
#delete from the nzblog so it will always find the most current downloads. Nzblog has issueid, but starts with ArcID
myDB.action('DELETE from nzblog WHERE IssueID LIKE ?', [stid])
logger.info("[DELETE-ARC] Removed " + str(StoryArcID) + " from Story Arcs.")
elif IssueArcID:
if manual == 'added':
myDB.action('DELETE from storyarcs WHERE IssueArcID=?', [IssueArcID])
else:
myDB.upsert("storyarcs", {"Manual": 'deleted'}, {"IssueArcID": IssueArcID})
#myDB.action('DELETE from storyarcs WHERE IssueArcID=?', [IssueArcID])
logger.info("[DELETE-ARC] Removed " + str(IssueArcID) + " from the Story Arc.")
elif AllRead:
myDB.action("DELETE from readlist WHERE Status='Read'")
logger.info("[DELETE-ALL-READ] Removed All issues that have been marked as Read from Reading List")
removefromreadlist.exposed = True
def markasRead(self, IssueID=None, IssueArcID=None):
read = readinglist.Readinglist(IssueID, IssueArcID)
read.markasRead()
markasRead.exposed = True
def addtoreadlist(self, IssueID):
read = readinglist.Readinglist(IssueID=IssueID)
read.addtoreadlist()
return
#raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % readlist['ComicID'])
addtoreadlist.exposed = True
def importReadlist(self, filename):
from xml.dom.minidom import parseString, Element
import random
myDB = db.DBConnection()
file = open(filename)
data = file.read()
file.close()
dom = parseString(data)
# of results
storyarc = dom.getElementsByTagName('Name')[0].firstChild.wholeText
tracks = dom.getElementsByTagName('Book')
i = 1
node = dom.documentElement
logger.fdebug("there are " + str(len(tracks)) + " issues in the story-arc: " + str(storyarc))
#generate a random number for the ID, and tack on the total issue count to the end as a str :)
storyarcid = str(random.randint(1000, 9999)) + str(len(tracks))
i = 1
for book_element in tracks:
st_issueid = str(storyarcid) + "_" + str(random.randint(1000, 9999))
comicname = book_element.getAttribute('Series')
logger.fdebug("comic: " + comicname)
comicnumber = book_element.getAttribute('Number')
logger.fdebug("number: " + str(comicnumber))
comicvolume = book_element.getAttribute('Volume')
logger.fdebug("volume: " + str(comicvolume))
comicyear = book_element.getAttribute('Year')
logger.fdebug("year: " + str(comicyear))
CtrlVal = {"IssueArcID": st_issueid}
NewVals = {"StoryArcID": storyarcid,
"ComicName": comicname,
"IssueNumber": comicnumber,
"SeriesYear": comicvolume,
"IssueYear": comicyear,
"StoryArc": storyarc,
"ReadingOrder": i,
"TotalIssues": len(tracks)}
myDB.upsert("storyarcs", NewVals, CtrlVal)
i+=1
# Now we either load in all of the issue data for series' already on the watchlist,
# or we dynamically load them from CV and write to the db.
#this loads in all the series' that have multiple entries in the current story arc.
Arc_MultipleSeries = myDB.select("SELECT * FROM storyarcs WHERE StoryArcID=? AND IssueID is NULL GROUP BY ComicName HAVING (COUNT(ComicName) > 1)", [storyarcid])
if Arc_MultipleSeries is None:
logger.info('Detected 0 series that have multiple entries in this Story Arc. Continuing.')
else:
AMS = []
for Arc_MS in Arc_MultipleSeries:
print Arc_MS
#the purpose of this loop is to loop through the multiple entries, pulling out the lowest & highest issue numbers
#along with the publication years in order to help the auto-detector attempt to figure out what the series is on CV.
#.schema storyarcs
#(StoryArcID TEXT, ComicName TEXT, IssueNumber TEXT, SeriesYear TEXT, IssueYEAR TEXT, StoryArc TEXT, TotalIssues TEXT,
# Status TEXT, inCacheDir TEXT, Location TEXT, IssueArcID TEXT, ReadingOrder INT, IssueID TEXT);
AMS.append({"StoryArcID": Arc_MS['StoryArcID'],
"ComicName": Arc_MS['ComicName'],
"SeriesYear": Arc_MS['SeriesYear'],
"IssueYear": Arc_MS['IssueYear'],
"IssueID": Arc_MS['IssueID'],
"highvalue": '0',
"lowvalue": '9999',
"yearRANGE": [str(Arc_MS['SeriesYear'])]}) #Arc_MS['SeriesYear']})
for MSCheck in AMS:
thischk = myDB.select('SELECT * FROM storyarcs WHERE ComicName=? AND SeriesYear=?', [MSCheck['ComicName'], MSCheck['SeriesYear']])
for tchk in thischk:
if helpers.issuedigits(tchk['IssueNumber']) > helpers.issuedigits(MSCheck['highvalue']):
for key in MSCheck.keys():
if key == "highvalue":
MSCheck[key] = tchk['IssueNumber']
if helpers.issuedigits(tchk['IssueNumber']) < helpers.issuedigits(MSCheck['lowvalue']):
for key in MSCheck.keys():
if key == "lowvalue":
MSCheck[key] = tchk['IssueNumber']
logger.fdebug(str(tchk['IssueYear']))
logger.fdebug(MSCheck['yearRANGE'])
if str(tchk['IssueYear']) not in str(MSCheck['yearRANGE']):
for key in MSCheck.keys():
if key == "yearRANGE":
MSCheck[key].append(str(tchk['IssueYear']))
#write out here
#logger.fdebug(str(MSCheck))
#now we load in the list without the multiple entries (ie. series that appear only once in the cbl and don't have an IssueID)
Arc_Issues = myDB.select("SELECT * FROM storyarcs WHERE StoryArcID=? AND IssueID is NULL GROUP BY ComicName HAVING (COUNT(ComicName) = 1)", [storyarcid])
if Arc_Issues is None:
logger.fdebug('No individual series detected within the Reading list (series that only appear once).')
else:
logger.fdebug('Detected series that occur only once in the Reading List.')
for AI in Arc_Issues:
logger.fdebug('Detected ' + AI['ComicName'] + ' (' + AI['SeriesYear'] + ') #' + AI['IssueNumber'])
AMS.append({"StoryArcID": AI['StoryArcID'],
"ComicName": AI['ComicName'],
"SeriesYear": AI['SeriesYear'],
"IssueYear": AI['IssueYear'],
"IssueID": AI['IssueID'],
"highvalue": AI['IssueNumber'],
"lowvalue": AI['IssueNumber'],
"yearRANGE": AI['IssueYear']})
logger.fdebug('AMS:' + str(AMS))
logger.fdebug('I need to now try to populate ' + str(len(AMS)) + ' series.')
Arc_Data = []
for duh in AMS:
mode='series'
sresults = mb.findComic(duh['ComicName'], mode, issue=duh['highvalue'], limityear=duh['yearRANGE'])
type='comic'
if len(sresults) == 1:
sr = sresults[0]
logger.info('Only one result...automagik-mode enabled for ' + duh['ComicName'] + ' :: ' + str(sr['comicid']) + ' :: Publisher : ' + str(sr['publisher']))
issues = mylar.cv.getComic(sr['comicid'], 'issue')
isscnt = len(issues['issuechoice'])
logger.info('isscnt : ' + str(isscnt))
chklist = myDB.select('SELECT * FROM storyarcs WHERE StoryArcID=? AND ComicName=? AND SeriesYear=?', [duh['StoryArcID'], duh['ComicName'], duh['SeriesYear']])
if chklist is None:
logger.error('I did not find anything in the Story Arc. Something is probably wrong.')
continue
else:
n = 0
while (n <= isscnt):
try:
islval = issues['issuechoice'][n]
except IndexError:
break
for d in chklist:
if islval['Issue_Number'] == d['IssueNumber']:
logger.info('[' + str(islval['Issue_ID']) + '] matched on Issue Number for ' + duh['ComicName'] + ' #' + str(d['IssueNumber']))
logger.info('I should write these dates: ' + islval['Issue_Date'] + ' -- ' + islval['Store_Date'])
Arc_Data.append({"StoryArcID": duh['StoryArcID'],
"IssueArcID": d['IssueArcID'],
"ComicID": islval['Comic_ID'],
"IssueID": islval['Issue_ID'],
"Issue_Number": islval['Issue_Number'],
"Issue_Date": islval['Issue_Date'],
"Publisher": sr['publisher'],
"Store_Date": islval['Store_Date']})
break
n+=1
#the below cresults will auto-add and cycle through until all are added to watchlist
#cresults = importer.addComictoDB(sr['comicid'],"no",None)
else:
logger.fdebug('Returning results to screen - more than one possibility.')
resultset = 0
logger.info('I need to update ' + str(len(Arc_Data)) + ' issues in this Reading List with CV Issue Data.')
if len(Arc_Data) > 0:
for AD in Arc_Data:
newCtrl = {"IssueArcID": AD['IssueArcID']}
newVals = {"ComicID": AD['ComicID'],
"IssueID": AD['IssueID'],
"Publisher": AD['Publisher'],
"IssueDate": AD['Issue_Date'],
"ReleaseDate": AD['Store_Date']}
myDB.upsert("storyarcs", newVals, newCtrl)
raise cherrypy.HTTPRedirect("detailStoryArc?StoryArcID=%s&StoryArcName=%s" % (storyarcid, storyarc))
importReadlist.exposed = True
def ArcWatchlist(self,StoryArcID=None):
myDB = db.DBConnection()
if StoryArcID:
ArcWatch = myDB.select("SELECT * FROM storyarcs WHERE StoryArcID=?", [StoryArcID])
else:
ArcWatch = myDB.select("SELECT * FROM storyarcs")
if ArcWatch is None:
logger.info("No Story Arcs to search")
else:
#cycle through the story arcs here for matches on the watchlist
arcname = ArcWatch[0]['StoryArc']
arcdir = helpers.filesafe(arcname)
arcpub = ArcWatch[0]['Publisher']
if arcpub is None:
arcpub = ArcWatch[0]['IssuePublisher']
lowyear = 9999
maxyear = 0
for la in ArcWatch:
if la['IssueDate'] is None:
continue
else:
if int(la['IssueDate'][:4]) > maxyear:
maxyear = int(la['IssueDate'][:4])
if int(la['IssueDate'][:4]) < lowyear:
lowyear = int(la['IssueDate'][:4])
if maxyear == 0:
spanyears = la['SeriesYear']
elif lowyear == maxyear:
spanyears = str(maxyear)
else:
spanyears = '%s - %s' % (lowyear, maxyear)
logger.info('arcpub: %s' % arcpub)
dstloc = helpers.arcformat(arcdir, spanyears, arcpub)
filelist = None
if dstloc is not None:
if not os.path.isdir(dstloc):
if mylar.CONFIG.STORYARCDIR:
logger.info('Story Arc Directory [%s] does not exist! - attempting to create now.' % dstloc)
else:
logger.info('Story Arc Grab-Bag Directory [%s] does not exist! - attempting to create now.' % dstloc)
checkdirectory = filechecker.validateAndCreateDirectory(dstloc, True)
if not checkdirectory:
logger.warn('Error trying to validate/create directory. Aborting this process at this time.')
return
if all([mylar.CONFIG.CVINFO, mylar.CONFIG.STORYARCDIR]):
if not os.path.isfile(os.path.join(dstloc, "cvinfo")) or mylar.CONFIG.CV_ONETIMER:
logger.fdebug('Generating cvinfo file for story-arc.')
with open(os.path.join(dstloc, "cvinfo"), "w") as text_file:
if any([ArcWatch[0]['StoryArcID'] == ArcWatch[0]['CV_ArcID'], ArcWatch[0]['CV_ArcID'] is None]):
cvinfo_arcid = ArcWatch[0]['StoryArcID']
else:
cvinfo_arcid = ArcWatch[0]['CV_ArcID']
text_file.write('https://comicvine.gamespot.com/storyarc/4045-' + str(cvinfo_arcid))
if mylar.CONFIG.ENFORCE_PERMS:
filechecker.setperms(os.path.join(dstloc, 'cvinfo'))
#get the list of files within the storyarc directory, if any.
if mylar.CONFIG.STORYARCDIR:
fchk = filechecker.FileChecker(dir=dstloc, watchcomic=None, Publisher=None, sarc='true', justparse=True)
filechk = fchk.listFiles()
fccnt = filechk['comiccount']
logger.fdebug('[STORY ARC DIRECTORY] %s files exist within this directory.' % fccnt)
if fccnt > 0:
filelist = filechk['comiclist']
logger.info(filechk)
arc_match = []
wantedlist = []
sarc_title = None
showonreadlist = 1 # 0 won't show storyarcissues on storyarcs main page, 1 will show
for arc in ArcWatch:
newStatus = 'Skipped'
if arc['Manual'] == 'deleted':
continue
sarc_title = arc['StoryArc']
logger.fdebug('[%s] %s : %s' % (arc['StoryArc'], arc['ComicName'], arc['IssueNumber']))
matcheroso = "no"
#fc = filechecker.FileChecker(watchcomic=arc['ComicName'])
#modi_names = fc.dynamic_replace(arc['ComicName'])
#mod_arc = re.sub('[\|\s]', '', modi_names['mod_watchcomic'].lower()).strip() #is from the arc db
comics = myDB.select("SELECT * FROM comics WHERE DynamicComicName IN (?) COLLATE NOCASE", [arc['DynamicComicName']])
for comic in comics:
mod_watch = comic['DynamicComicName'] #is from the comics db
if re.sub('[\|\s]','', mod_watch.lower()).strip() == re.sub('[\|\s]', '', arc['DynamicComicName'].lower()).strip():
logger.fdebug("initial name match - confirming issue # is present in series")
if comic['ComicID'][:1] == 'G':
# if it's a multi-volume series, it's decimalized - let's get rid of the decimal.
GCDissue, whocares = helpers.decimal_issue(arc['IssueNumber'])
GCDissue = int(GCDissue) / 1000
if '.' not in str(GCDissue):
GCDissue = '%s.00' % GCDissue
logger.fdebug("issue converted to %s" % GCDissue)
isschk = myDB.selectone("SELECT * FROM issues WHERE Issue_Number=? AND ComicID=?", [str(GCDissue), comic['ComicID']]).fetchone()
else:
issue_int = helpers.issuedigits(arc['IssueNumber'])
logger.fdebug('int_issue = %s' % issue_int)
isschk = myDB.selectone("SELECT * FROM issues WHERE Int_IssueNumber=? AND ComicID=?", [issue_int, comic['ComicID']]).fetchone() #AND STATUS !='Snatched'", [issue_int, comic['ComicID']]).fetchone()
if isschk is None:
logger.fdebug('We matched on name, but issue %s doesn\'t exist for %s' % (arc['IssueNumber'], comic['ComicName']))
else:
#this gets ugly - if the name matches and the issue, it could still be wrong series
#use series year to break it down further.
logger.fdebug('COMIC-comicyear: %s' % comic['ComicYear'])
logger.fdebug('B4-ARC-seriesyear: %s' % arc['SeriesYear'])
if any([arc['SeriesYear'] is None, arc['SeriesYear'] == 'None']):
vy = '2099-00-00'
for x in isschk:
if any([x['IssueDate'] is None, x['IssueDate'] == '0000-00-00']):
sy = x['StoreDate']
if any([sy is None, sy == '0000-00-00']):
continue
else:
sy = x['IssueDate']
if sy < vy:
v_seriesyear = sy
seriesyear = v_seriesyear
logger.info('No Series year set. Discovered & set to %s' % seriesyear)
else:
seriesyear = arc['SeriesYear']
logger.fdebug('ARC-seriesyear: %s' % seriesyear)
if int(comic['ComicYear']) != int(seriesyear):
logger.fdebug('Series years are different - discarding match. %s != %s' % (comic['ComicYear'], seriesyear))
else:
logger.fdebug('issue #: %s is present!' % arc['IssueNumber'])
logger.fdebug('Comicname: %s' % arc['ComicName'])
logger.fdebug('ComicID: %s' % isschk['ComicID'])
logger.fdebug('Issue: %s' % arc['IssueNumber'])
logger.fdebug('IssueArcID: %s' % arc['IssueArcID'])
#gather the matches now.
arc_match.append({
"match_storyarc": arc['StoryArc'],
"match_name": arc['ComicName'],
"match_id": isschk['ComicID'],
"match_issue": arc['IssueNumber'],
"match_issuearcid": arc['IssueArcID'],
"match_seriesyear": comic['ComicYear'],
"match_readingorder": arc['ReadingOrder'],
"match_filedirectory": comic['ComicLocation'], #series directory path
"destination_location": dstloc}) #path to given storyarc / grab-bag directory
matcheroso = "yes"
break
if matcheroso == "no":
logger.fdebug('[NO WATCHLIST MATCH] Unable to find a match for %s :#%s' % (arc['ComicName'], arc['IssueNumber']))
wantedlist.append({
"ComicName": arc['ComicName'],
"IssueNumber": arc['IssueNumber'],
"IssueYear": arc['IssueYear']})
if filelist is not None and mylar.CONFIG.STORYARCDIR:
logger.fdebug('[NO WATCHLIST MATCH] Checking against local Arc directory for given issue.')
fn = 0
valids = [x for x in filelist if re.sub('[\|\s]','', x['dynamic_name'].lower()).strip() == re.sub('[\|\s]','', arc['DynamicComicName'].lower()).strip()]
logger.fdebug('valids: %s' % valids)
if len(valids) > 0:
for tmpfc in valids: #filelist:
haveissue = "no"
issuedupe = "no"
temploc = tmpfc['issue_number'].replace('_', ' ')
fcdigit = helpers.issuedigits(arc['IssueNumber'])
int_iss = helpers.issuedigits(temploc)
if int_iss == fcdigit:
logger.fdebug('%s Issue #%s already present in StoryArc directory' % (arc['ComicName'], arc['IssueNumber']))
#update storyarcs db to reflect status.
rr_rename = False
if mylar.CONFIG.READ2FILENAME:
readorder = helpers.renamefile_readingorder(arc['ReadingOrder'])
if all([tmpfc['reading_order'] is not None, int(readorder) != int(tmpfc['reading_order']['reading_sequence'])]):
logger.warn('reading order sequence has changed for this issue from %s to %s' % (tmpfc['reading_order']['reading_sequence'], readorder))
rr_rename = True
dfilename = '%s-%s' % (readorder, tmpfc['reading_order']['filename'])
elif tmpfc['reading_order'] is None:
dfilename = '%s-%s' % (readorder, tmpfc['comicfilename'])
else:
dfilename = '%s-%s' % (readorder, tmpfc['reading_order']['filename'])
else:
dfilename = tmpfc['comicfilename']
if all([tmpfc['sub'] is not None, tmpfc['sub'] != 'None']):
loc_path = os.path.join(tmpfc['comiclocation'], tmpfc['sub'], dfilename)
else:
loc_path = os.path.join(tmpfc['comiclocation'], dfilename)
if rr_rename:
logger.fdebug('Now re-sequencing file to : %s' % dfilename)
os.rename(os.path.join(tmpfc['comiclocation'],tmpfc['comicfilename']), loc_path)
newStatus = 'Downloaded'
newVal = {"Status": newStatus,
"Location": loc_path} #dfilename}
ctrlVal = {"IssueArcID": arc['IssueArcID']}
myDB.upsert("storyarcs", newVal, ctrlVal)
break
else:
newStatus = 'Skipped'
fn+=1
if newStatus == 'Skipped':
#this will set all None Status' to Skipped (at least initially)
newVal = {"Status": "Skipped"}
ctrlVal = {"IssueArcID": arc['IssueArcID']}
myDB.upsert("storyarcs", newVal, ctrlVal)
continue
newVal = {"Status": "Skipped"}
ctrlVal = {"IssueArcID": arc['IssueArcID']}
myDB.upsert("storyarcs", newVal, ctrlVal)
logger.fdebug('%s issues currently exist on your watchlist that are within this arc. Analyzing...' % len(arc_match))
for m_arc in arc_match:
#now we cycle through the issues looking for a match.
#issue = myDB.selectone("SELECT * FROM issues where ComicID=? and Issue_Number=?", [m_arc['match_id'], m_arc['match_issue']]).fetchone()
issue = myDB.selectone("SELECT a.Issue_Number, a.Status, a.IssueID, a.ComicName, a.IssueDate, a.Location, b.readingorder FROM issues AS a INNER JOIN storyarcs AS b ON a.comicid = b.comicid where a.comicid=? and a.issue_number=?", [m_arc['match_id'], m_arc['match_issue']]).fetchone()
if issue is None: pass
else:
logger.fdebug('issue: %s ... %s' % (issue['Issue_Number'], m_arc['match_issue']))
if issue['Issue_Number'] == m_arc['match_issue']:
logger.fdebug('We matched on %s for %s' % (issue['Issue_Number'], m_arc['match_name']))
if issue['Status'] == 'Downloaded' or issue['Status'] == 'Archived' or issue['Status'] == 'Snatched':
if showonreadlist:
showctrlVal = {"IssueID": issue['IssueID']}
shownewVal = {"ComicName": issue['ComicName'],
"Issue_Number": issue['Issue_Number'],
"IssueDate": issue['IssueDate'],
"SeriesYear": m_arc['match_seriesyear'],
"ComicID": m_arc['match_id']}
myDB.upsert("readlist", shownewVal, showctrlVal)
logger.fdebug('Already have %s : #%s' % (issue['ComicName'], issue['Issue_Number']))
if issue['Location'] is not None:
issloc = os.path.join(m_arc['match_filedirectory'], issue['Location'])
else:
issloc = None
location_path = issloc
if issue['Status'] == 'Downloaded':
#check multiple destination directory usage here.
if not os.path.isfile(issloc):
try:
if all([mylar.CONFIG.MULTIPLE_DEST_DIRS is not None, mylar.CONFIG.MULTIPLE_DEST_DIRS != 'None', os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(m_arc['match_filedirectory'])) != issloc, os.path.exists(os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(m_arc['match_filedirectory'])))]):
issloc = os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(m_arc['match_filedirectory']), issue['Location'])
if not os.path.isfile(issloc):
logger.warn('Source file cannot be located. Please do a Recheck for the specific series to ensure everything is correct.')
continue
except:
pass
logger.fdebug('source location set to : %s' % issloc)
if all([mylar.CONFIG.STORYARCDIR, mylar.CONFIG.COPY2ARCDIR]):
logger.fdebug('Destination location set to : %s' % m_arc['destination_location'])
logger.fdebug('Attempting to copy into StoryArc directory')
#copy into StoryArc directory...
#need to make sure the file being copied over isn't already present in the directory either with a different filename,
#or different reading order.
rr_rename = False
if mylar.CONFIG.READ2FILENAME:
readorder = helpers.renamefile_readingorder(m_arc['match_readingorder'])
if all([m_arc['match_readingorder'] is not None, int(readorder) != int(m_arc['match_readingorder'])]):
logger.warn('Reading order sequence has changed for this issue from %s to %s' % (m_arc['match_reading_order'], readorder))
rr_rename = True
dfilename = '%s-%s' % (readorder, issue['Location'])
elif m_arc['match_readingorder'] is None:
dfilename = '%s-%s' % (readorder, issue['Location'])
else:
dfilename = '%s-%s' % (readorder, issue['Location'])
else:
dfilename = issue['Location']
#dfilename = str(readorder) + "-" + issue['Location']
#else:
#dfilename = issue['Location']
dstloc = os.path.join(m_arc['destination_location'], dfilename)
if rr_rename:
logger.fdebug('Now re-sequencing COPIED file to : %s' % dfilename)
os.rename(issloc, dstloc)
if not os.path.isfile(dstloc):
logger.fdebug('Copying %s to %s' % (issloc, dstloc))
try:
fileoperation = helpers.file_ops(issloc, dstloc, arc=True)
if not fileoperation:
raise OSError
except (OSError, IOError):
logger.error('Failed to %s %s - check directories and manually re-run.' % (mylar.CONFIG.FILE_OPTS, issloc))
continue
else:
logger.fdebug('Destination file exists: %s' % dstloc)
location_path = dstloc
else:
location_path = issloc
ctrlVal = {"IssueArcID": m_arc['match_issuearcid']}
newVal = {'Status': issue['Status'],
'IssueID': issue['IssueID'],
'Location': location_path}
myDB.upsert("storyarcs",newVal,ctrlVal)
else:
logger.fdebug('We don\'t have %s : #%s' % (issue['ComicName'], issue['Issue_Number']))
ctrlVal = {"IssueArcID": m_arc['match_issuearcid']}
newVal = {"Status": issue['Status'], #"Wanted",
"IssueID": issue['IssueID']}
myDB.upsert("storyarcs", newVal, ctrlVal)
logger.info('Marked %s :#%s as %s' % (issue['ComicName'], issue['Issue_Number'], issue['Status']))
arcstats = self.storyarc_main(StoryArcID)
logger.info('[STORY-ARCS] Completed Missing/Recheck Files for %s [%s / %s]' % (arcname, arcstats['Have'], arcstats['TotalIssues']))
return
ArcWatchlist.exposed = True
def SearchArcIssues(self, **kwargs):
threading.Thread(target=self.ReadGetWanted, kwargs=kwargs).start()
SearchArcIssues.exposed = True
def ReadGetWanted(self, StoryArcID):
# this will queue up (ie. make 'Wanted') issues in a given Story Arc that are 'Not Watched'
stupdate = []
mode = 'story_arc'
myDB = db.DBConnection()
wantedlist = myDB.select("SELECT * FROM storyarcs WHERE StoryArcID=? AND Status != 'Downloaded' AND Status !='Archived' AND Status !='Snatched'", [StoryArcID])
if wantedlist is not None:
for want in wantedlist:
print want
issuechk = myDB.selectone("SELECT a.Type, a.ComicYear, b.ComicName, b.Issue_Number, b.ComicID, b.IssueID FROM comics as a INNER JOIN issues as b on a.ComicID = b.ComicID WHERE b.IssueID=?", [want['IssueArcID']]).fetchone()
SARC = want['StoryArc']
IssueArcID = want['IssueArcID']
Publisher = want['Publisher']
if issuechk is None:
# none means it's not a 'watched' series
s_comicid = want['ComicID'] #None
s_issueid = want['IssueArcID'] #None
BookType = want['Type']
stdate = want['ReleaseDate']
issdate = want['IssueDate']
logger.fdebug("-- NOT a watched series queue.")
logger.fdebug('%s -- #%s' % (want['ComicName'], want['IssueNumber']))
logger.fdebug('Story Arc %s : queueing the selected issue...' % SARC)
logger.fdebug('IssueArcID : %s' % IssueArcID)
logger.fdebug('ComicID: %s --- IssueID: %s' % (s_comicid, s_issueid)) # no comicid in issues table.
logger.fdebug('ReleaseDate: %s --- IssueDate: %s' % (stdate, issdate))
issueyear = want['IssueYEAR']
logger.fdebug('IssueYear: %s' % issueyear)
if issueyear is None or issueyear == 'None':
try:
logger.fdebug('issdate:' + str(issdate))
issueyear = issdate[:4]
if not issueyear.startswith('19') and not issueyear.startswith('20'):
issueyear = stdate[:4]
except:
issueyear = stdate[:4]
logger.fdebug('ComicYear: %s' % want['SeriesYear'])
passinfo = {'issueid': s_issueid,
'comicname': want['ComicName'],
'seriesyear': want['SeriesYear'],
'comicid': s_comicid,
'issuenumber': want['IssueNumber'],
'booktype': BookType}
#oneoff = True ?
else:
# it's a watched series
s_comicid = issuechk['ComicID']
s_issueid = issuechk['IssueID']
logger.fdebug("-- watched series queue.")
logger.fdebug('%s --- #%s' % (issuechk['ComicName'], issuechk['Issue_Number']))
passinfo = {'issueid': s_issueid,
'comicname': issuechk['ComicName'],
'seriesyear': issuechk['SeriesYear'],
'comicid': s_comicid,
'issuenumber': issuechk['Issue_Number'],
'booktype': issuechk['Type']}
mylar.SEARCH_QUEUE.put(passinfo)
#if foundcom['status'] is True:
# logger.fdebug('sucessfully found.')
# #update the status - this is necessary for torrents as they are in 'snatched' status.
# updater.foundsearch(s_comicid, s_issueid, mode=mode, provider=prov, SARC=SARC, IssueArcID=IssueArcID)
#else:
# logger.fdebug('not sucessfully found.')
# stupdate.append({"Status": "Wanted",
# "IssueArcID": IssueArcID,
# "IssueID": s_issueid})
watchlistchk = myDB.select("SELECT * FROM storyarcs WHERE StoryArcID=? AND Status='Wanted'", [StoryArcID])
if watchlistchk is not None:
for watchchk in watchlistchk:
logger.fdebug('Watchlist hit - %s' % watchchk['ComicName'])
issuechk = myDB.selectone("SELECT a.Type, a.ComicYear, b.ComicName, b.Issue_Number, b.ComicID, b.IssueID FROM comics as a INNER JOIN issues as b on a.ComicID = b.ComicID WHERE b.IssueID=?", [watchchk['IssueArcID']]).fetchone()
SARC = watchchk['StoryArc']
IssueArcID = watchchk['IssueArcID']
if issuechk is None:
# none means it's not a 'watched' series
try:
s_comicid = watchchk['ComicID']
except:
s_comicid = None
try:
s_issueid = watchchk['IssueArcID']
except:
s_issueid = None
logger.fdebug("-- NOT a watched series queue.")
logger.fdebug('%s -- #%s' % (watchchk['ComicName'], watchchk['IssueNumber']))
logger.fdebug('Story Arc : %s queueing up the selected issue...' % SARC)
logger.fdebug('IssueArcID : %s' % IssueArcID)
try:
issueyear = watchchk['IssueYEAR']
logger.fdebug('issueYEAR : %s' % issueyear)
except:
try:
issueyear = watchchk['IssueDate'][:4]
except:
issueyear = watchchk['ReleaseDate'][:4]
stdate = watchchk['ReleaseDate']
issdate = watchchk['IssueDate']
logger.fdebug('issueyear : %s' % issueyear)
logger.fdebug('comicname : %s' % watchchk['ComicName'])
logger.fdebug('issuenumber : %s' % watchchk['IssueNumber'])
logger.fdebug('comicyear : %s' % watchchk['SeriesYear'])
#logger.info('publisher : ' + watchchk['IssuePublisher']) <-- no publisher in table
logger.fdebug('SARC : %s' % SARC)
logger.fdebug('IssueArcID : %s' % IssueArcID)
passinfo = {'issueid': s_issueid,
'comicname': watchchk['ComicName'],
'seriesyear': watchchk['SeriesYear'],
'comicid': s_comicid,
'issuenumber': watchchk['IssueNumber'],
'booktype': watchchk['Type']}
#foundcom, prov = search.search_init(ComicName=watchchk['ComicName'], IssueNumber=watchchk['IssueNumber'], ComicYear=issueyear, SeriesYear=watchchk['SeriesYear'], Publisher=None, IssueDate=issdate, StoreDate=stdate, IssueID=s_issueid, SARC=SARC, IssueArcID=IssueArcID, oneoff=True)
else:
# it's a watched series
s_comicid = issuechk['ComicID']
s_issueid = issuechk['IssueID']
logger.fdebug('-- watched series queue.')
logger.fdebug('%s -- #%s' % (issuechk['ComicName'], issuechk['Issue_Number']))
passinfo = {'issueid': s_issueid,
'comicname': issuechk['ComicName'],
'seriesyear': issuechk['SeriesYear'],
'comicid': s_comicid,
'issuenumber': issuechk['Issue_Number'],
'booktype': issuechk['Type']}
#foundcom, prov = search.search_init(ComicName=issuechk['ComicName'], IssueNumber=issuechk['Issue_Number'], ComicYear=issuechk['IssueYear'], SeriesYear=issuechk['SeriesYear'], Publisher=None, IssueDate=None, StoreDate=issuechk['ReleaseDate'], IssueID=issuechk['IssueID'], AlternateSearch=None, UseFuzzy=None, ComicVersion=None, SARC=SARC, IssueArcID=IssueArcID, mode=None, rsscheck=None, ComicID=None)
mylar.SEARCH_QUEUE.put(passinfo)
#if foundcom['status'] is True:
# updater.foundsearch(s_comicid, s_issueid, mode=mode, provider=prov, SARC=SARC, IssueArcID=IssueArcID)
#else:
# logger.fdebug('Watchlist issue not sucessfully found')
# logger.fdebug('issuearcid: %s' % IssueArcID)
# logger.fdebug('issueid: %s' % s_issueid)
# stupdate.append({"Status": "Wanted",
# "IssueArcID": IssueArcID,
# "IssueID": s_issueid})
if len(stupdate) > 0:
logger.fdebug('%s issues need to get updated to Wanted Status' % len(stupdate))
for st in stupdate:
ctrlVal = {'IssueArcID': st['IssueArcID']}
newVal = {'Status': st['Status']}
if st['IssueID']:
if st['IssueID']:
logger.fdebug('issueid: %s' %st['IssueID'])
newVal['IssueID'] = st['IssueID']
myDB.upsert("storyarcs", newVal, ctrlVal)
ReadGetWanted.exposed = True
def ReadMassCopy(self, StoryArcID, StoryArcName):
#this copies entire story arcs into the /cache/<storyarc> folder
#alternatively, it will copy the issues individually directly to a 3rd party device (ie.tablet)
myDB = db.DBConnection()
copylist = myDB.select("SELECT * FROM readlist WHERE StoryArcID=? AND Status='Downloaded'", [StoryArcID])
if copylist is None:
logger.fdebug("You don't have any issues from " + StoryArcName + ". Aborting Mass Copy.")
return
else:
dst = os.path.join(mylar.CONFIG.CACHE_DIR, StoryArcName)
for files in copylist:
copyloc = files['Location']
ReadMassCopy.exposed = True
def logs(self):
return serve_template(templatename="logs.html", title="Log", lineList=mylar.LOGLIST)
logs.exposed = True
def config_dump(self):
return serve_template(templatename="config_dump.html", title="Config Listing", lineList=mylar.CONFIG)
config_dump.exposed = True
def clearLogs(self):
mylar.LOGLIST = []
logger.info("Web logs cleared")
raise cherrypy.HTTPRedirect("logs")
clearLogs.exposed = True
def toggleVerbose(self):
if mylar.LOG_LEVEL != 2:
mylar.LOG_LEVEL = 2
else:
mylar.LOG_LEVEL = 1
if logger.LOG_LANG.startswith('en'):
logger.initLogger(console=not mylar.QUIET, log_dir=mylar.CONFIG.LOG_DIR, max_logsize=mylar.CONFIG.MAX_LOGSIZE, max_logfiles=mylar.CONFIG.MAX_LOGFILES, loglevel=mylar.LOG_LEVEL)
else:
logger.mylar_log.stopLogger()
logger.mylar_log.initLogger(loglevel=mylar.LOG_LEVEL, log_dir=mylar.CONFIG.LOG_DIR, max_logsize=mylar.CONFIG.MAX_LOGSIZE, max_logfiles=mylar.CONFIG.MAX_LOGFILES)
#mylar.VERBOSE = not mylar.VERBOSE
#logger.initLogger(console=not mylar.QUIET,
# log_dir=mylar.CONFIG.LOG_DIR, verbose=mylar.VERBOSE)
if mylar.LOG_LEVEL == 2:
logger.info("Verbose (DEBUG) logging is enabled")
logger.debug("If you can read this message, debug logging is now working")
else:
logger.info("normal (INFO) logging is now enabled")
raise cherrypy.HTTPRedirect("logs")
toggleVerbose.exposed = True
def getLog(self, iDisplayStart=0, iDisplayLength=100, iSortCol_0=0, sSortDir_0="desc", sSearch="", **kwargs):
iDisplayStart = int(iDisplayStart)
iDisplayLength = int(iDisplayLength)
filtered = []
if sSearch == "" or sSearch == None:
filtered = mylar.LOGLIST[::]
else:
filtered = [row for row in mylar.LOGLIST for column in row if sSearch.lower() in column.lower()]
sortcolumn = 0
if iSortCol_0 == '1':
sortcolumn = 2
elif iSortCol_0 == '2':
sortcolumn = 1
filtered.sort(key=lambda x: x[sortcolumn], reverse=sSortDir_0 == "desc")
rows = filtered[iDisplayStart:(iDisplayStart + iDisplayLength)]
rows = [[row[0], row[2], row[1]] for row in rows]
return json.dumps({
'iTotalDisplayRecords': len(filtered),
'iTotalRecords': len(mylar.LOGLIST),
'aaData': rows,
})
getLog.exposed = True
def getConfig(self, iDisplayStart=0, iDisplayLength=100, iSortCol_0=0, sSortDir_0="desc", sSearch="", **kwargs):
iDisplayStart = int(iDisplayStart)
iDisplayLength = int(iDisplayLength)
unfiltered = []
for each_section in mylar.config.config.sections():
for k,v in mylar.config.config.items(each_section):
unfiltered.insert( 0, (k, v.decode('utf-8')) )
if sSearch == "" or sSearch == None:
logger.info('getConfig: No search terms.')
filtered = unfiltered
else:
logger.info('getConfig: Searching for ' + sSearch)
dSearch = {sSearch: '.'}
filtered = [row for row in unfiltered for column in row if sSearch.lower() in column.lower()]
sortcolumn = 0
if iSortCol_0 == '1':
sortcolumn = 2
elif iSortCol_0 == '2':
sortcolumn = 1
filtered.sort(key=lambda x: x[sortcolumn], reverse=sSortDir_0 == "desc")
rows = filtered[iDisplayStart:(iDisplayStart + iDisplayLength)]
return json.dumps({
'iTotalDisplayRecords': len(filtered),
'iTotalRecords': len(unfiltered),
'aaData': rows,
})
getConfig.exposed = True
def clearhistory(self, type=None):
myDB = db.DBConnection()
if type == 'all':
logger.info(u"Clearing all history")
myDB.action('DELETE from snatched')
else:
logger.info(u"Clearing history where status is %s" % type)
myDB.action('DELETE from snatched WHERE Status=?', [type])
if type == 'Processed':
myDB.action("DELETE from snatched WHERE Status='Post-Processed'")
raise cherrypy.HTTPRedirect("history")
clearhistory.exposed = True
def downloadLocal(self, IssueID=None, IssueArcID=None, ReadOrder=None, dir=None):
myDB = db.DBConnection()
issueDL = myDB.selectone("SELECT * FROM issues WHERE IssueID=?", [IssueID]).fetchone()
comicid = issueDL['ComicID']
#print ("comicid: " + str(comicid))
comic = myDB.selectone("SELECT * FROM comics WHERE ComicID=?", [comicid]).fetchone()
#---issue info
comicname = comic['ComicName']
issuenum = issueDL['Issue_Number']
issuedate = issueDL['IssueDate']
seriesyear = comic['ComicYear']
#---
issueLOC = comic['ComicLocation']
#print ("IssueLOC: " + str(issueLOC))
issueFILE = issueDL['Location']
#print ("IssueFILE: "+ str(issueFILE))
issuePATH = os.path.join(issueLOC, issueFILE)
#print ("IssuePATH: " + str(issuePATH))
# if dir is None, it's a normal copy to cache kinda thing.
# if dir is a path, then it's coming from the pullist as the location to put all the weekly comics
if dir is not None:
dstPATH = dir
else:
dstPATH = os.path.join(mylar.CONFIG.CACHE_DIR, issueFILE)
#print ("dstPATH: " + str(dstPATH))
if IssueID:
ISnewValueDict = {'inCacheDIR': 'True',
'Location': issueFILE}
if IssueArcID:
if mylar.CONFIG.READ2FILENAME:
#if it's coming from a StoryArc, check to see if we're appending the ReadingOrder to the filename
ARCissueFILE = ReadOrder + "-" + issueFILE
dstPATH = os.path.join(mylar.CONFIG.CACHE_DIR, ARCissueFILE)
ISnewValueDict = {'inCacheDIR': 'True',
'Location': issueFILE}
# issueDL = myDB.action("SELECT * FROM storyarcs WHERE IssueArcID=?", [IssueArcID]).fetchone()
# storyarcid = issueDL['StoryArcID']
# #print ("comicid: " + str(comicid))
# issueLOC = mylar.CONFIG.DESTINATION_DIR
# #print ("IssueLOC: " + str(issueLOC))
# issueFILE = issueDL['Location']
# #print ("IssueFILE: "+ str(issueFILE))
# issuePATH = os.path.join(issueLOC,issueFILE)
# #print ("IssuePATH: " + str(issuePATH))
# dstPATH = os.path.join(mylar.CONFIG.CACHE_DIR, issueFILE)
# #print ("dstPATH: " + str(dstPATH))
try:
shutil.copy2(issuePATH, dstPATH)
except IOError as e:
logger.error("Could not copy " + str(issuePATH) + " to " + str(dstPATH) + ". Copy to Cache terminated.")
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % comicid)
#logger.debug("sucessfully copied to cache...Enabling Download link")
controlValueDict = {'IssueID': IssueID}
RLnewValueDict = {'inCacheDIR': 'True',
'Location': issueFILE,
'ComicID': comicid,
'ComicName': comicname,
'Issue_Number': issuenum,
'SeriesYear': seriesyear,
'IssueDate': issuedate}
myDB.upsert("readlist", RLnewValueDict, controlValueDict)
myDB.upsert("issues", ISnewValueDict, controlValueDict)
if IssueArcID:
controlValueD = {'IssueArcID': IssueArcID}
newValueDict = {'inCacheDIR': 'True',
'Location': ARCissueFILE}
myDB.upsert("storyarcs", newValueDict, controlValueD)
#print("DB updated - Download link now enabled.")
downloadLocal.exposed = True
def MassWeeklyDownload(self, weeknumber=None, year=None, midweek=None, weekfolder=0, filename=None):
if filename is None:
mylar.CONFIG.WEEKFOLDER = bool(int(weekfolder))
mylar.CONFIG.writeconfig(values={'weekfolder': mylar.CONFIG.WEEKFOLDER})
raise cherrypy.HTTPRedirect("pullist")
# this will download all downloaded comics from the weekly pull list and throw them
# into a 'weekly' pull folder for those wanting to transfer directly to a 3rd party device.
myDB = db.DBConnection()
if mylar.CONFIG.WEEKFOLDER:
if mylar.CONFIG.WEEKFOLDER_LOC:
dstdir = mylar.CONFIG.WEEKFOLDER_LOC
else:
dstdir = mylar.CONFIG.DESTINATION_DIR
if mylar.CONFIG.WEEKFOLDER_FORMAT == 0:
#0 = YYYY-mm
desdir = os.path.join(dstdir, str(year) + '-' + str(weeknumber))
elif mylar.CONFIG.WEEKFOLDER_FORMAT == 1:
#1 = YYYY-mm-dd (midweek)
desdir = os.path.join(dstdir, str(midweek))
chkdir = filechecker.validateAndCreateDirectory(desdir, create=True, module='WEEKLY-FOLDER')
if not chkdir:
logger.warn('Unable to create weekly directory. Check location & permissions. Aborting Copy.')
return
else:
desdir = mylar.CONFIG.GRABBAG_DIR
issuelist = helpers.listIssues(weeknumber,year)
if issuelist is None: # nothing on the list, just go go gone
logger.info("There aren't any issues downloaded from this week yet.")
else:
iscount = 0
for issue in issuelist:
#logger.fdebug('Checking status of ' + issue['ComicName'] + ' #' + str(issue['Issue_Number']))
if issue['Status'] == 'Downloaded':
logger.info('Status Downloaded.')
self.downloadLocal(issue['IssueID'], dir=desdir)
logger.info("Copied " + issue['ComicName'] + " #" + str(issue['Issue_Number']) + " to " + desdir.encode('utf-8').strip())
iscount+=1
logger.info('I have copied ' + str(iscount) + ' issues from week #' + str(weeknumber) + ' pullist as requested.')
raise cherrypy.HTTPRedirect("pullist?week=%s&year=%s" % (weeknumber, year))
MassWeeklyDownload.exposed = True
def idirectory(self):
return serve_template(templatename="idirectory.html", title="Import a Directory")
idirectory.exposed = True
def confirmResult(self, comicname, comicid):
mode='series'
sresults = mb.findComic(comicname, mode, None)
type='comic'
return serve_template(templatename="searchresults.html", title='Import Results for: "' + comicname + '"', searchresults=sresults, type=type, imported='confirm', ogcname=comicid)
confirmResult.exposed = True
def Check_ImportStatus(self):
#logger.info('import_status: ' + mylar.IMPORT_STATUS)
return mylar.IMPORT_STATUS
Check_ImportStatus.exposed = True
def comicScan(self, path, scan=0, libraryscan=0, redirect=None, autoadd=0, imp_move=0, imp_paths=0, imp_rename=0, imp_metadata=0, forcescan=0):
import Queue
queue = Queue.Queue()
#save the values so they stick.
mylar.CONFIG.ADD_COMICS = autoadd
#too many problems for windows users, have to rethink this....
#if 'windows' in mylar.OS_DETECT.lower() and '\\\\?\\' not in path:
# #to handle long paths, let's append the '\\?\' to the path to allow for unicode windows api access
# path = "\\\\?\\" + path
mylar.CONFIG.COMIC_DIR = path
mylar.CONFIG.IMP_MOVE = bool(imp_move)
mylar.CONFIG.IMP_RENAME = bool(imp_rename)
mylar.CONFIG.IMP_METADATA = bool(imp_metadata)
mylar.CONFIG.IMP_PATHS = bool(imp_paths)
mylar.CONFIG.configure(update=True)
# Write the config
logger.info('Now updating config...')
mylar.CONFIG.writeconfig()
logger.info('forcescan is: ' + str(forcescan))
if mylar.IMPORTLOCK and forcescan == 1:
logger.info('Removing Current lock on import - if you do this AND another process is legitimately running, your causing your own problems.')
mylar.IMPORTLOCK = False
#thread the scan.
if scan == '1':
scan = True
mylar.IMPORT_STATUS = 'Now starting the import'
return self.ThreadcomicScan(scan, queue)
else:
scan = False
return
comicScan.exposed = True
def ThreadcomicScan(self, scan, queue):
thread_ = threading.Thread(target=librarysync.scanLibrary, name="LibraryScan", args=[scan, queue])
thread_.start()
thread_.join()
chk = queue.get()
while True:
if chk[0]['result'] == 'success':
yield chk[0]['result']
logger.info('Successfully scanned in directory. Enabling the importResults button now.')
mylar.IMPORTBUTTON = True #globally set it to ON after the scan so that it will be picked up.
mylar.IMPORT_STATUS = 'Import completed.'
break
else:
yield ckh[0]['result']
mylar.IMPORTBUTTON = False
break
return
ThreadcomicScan.exposed = True
def importResults(self):
myDB = db.DBConnection()
results = myDB.select("SELECT * FROM importresults WHERE WatchMatch is Null OR WatchMatch LIKE 'C%' group by DynamicName, Volume, Status COLLATE NOCASE")
#this is to get the count of issues;
res = []
countit = []
ann_cnt = 0
for result in results:
res.append(result)
for x in res:
if x['Volume']:
#because Volume gets stored as NULL in the db, we need to account for it coming into here as a possible None value.
countthis = myDB.select("SELECT count(*) FROM importresults WHERE DynamicName=? AND Volume=? AND Status=?", [x['DynamicName'],x['Volume'],x['Status']])
countannuals = myDB.select("SELECT count(*) FROM importresults WHERE DynamicName=? AND Volume=? AND IssueNumber LIKE 'Annual%' AND Status=?", [x['DynamicName'],x['Volume'],x['Status']])
else:
countthis = myDB.select("SELECT count(*) FROM importresults WHERE DynamicName=? AND Volume IS NULL AND Status=?", [x['DynamicName'],x['Status']])
countannuals = myDB.select("SELECT count(*) FROM importresults WHERE DynamicName=? AND Volume IS NULL AND IssueNumber LIKE 'Annual%' AND Status=?", [x['DynamicName'],x['Status']])
countit.append({"DynamicName": x['DynamicName'],
"Volume": x['Volume'],
"IssueCount": countthis[0][0],
"AnnualCount": countannuals[0][0],
"ComicName": x['ComicName'],
"DisplayName": x['DisplayName'],
"Volume": x['Volume'],
"ComicYear": x['ComicYear'],
"Status": x['Status'],
"ComicID": x['ComicID'],
"WatchMatch": x['WatchMatch'],
"ImportDate": x['ImportDate'],
"SRID": x['SRID']})
return serve_template(templatename="importresults.html", title="Import Results", results=countit) #results, watchresults=watchresults)
importResults.exposed = True
def ImportFilelisting(self, comicname, dynamicname, volume):
comicname = urllib.unquote_plus(helpers.conversion(comicname))
dynamicname = helpers.conversion(urllib.unquote_plus(dynamicname)) #urllib.unquote(dynamicname).decode('utf-8')
myDB = db.DBConnection()
if volume is None or volume == 'None':
results = myDB.select("SELECT * FROM importresults WHERE (WatchMatch is Null OR WatchMatch LIKE 'C%') AND DynamicName=? AND Volume IS NULL",[dynamicname])
else:
if not volume.lower().startswith('v'):
volume = 'v' + str(volume)
results = myDB.select("SELECT * FROM importresults WHERE (WatchMatch is Null OR WatchMatch LIKE 'C%') AND DynamicName=? AND Volume=?",[dynamicname,volume])
filelisting = '<table width="500"><tr><td>'
filelisting += '<center><b>Files that have been scanned in for:</b></center>'
if volume is None or volume == 'None':
filelisting += '<center><b>' + comicname + '</b></center></td></tr><tr><td>'
else:
filelisting += '<center><b>' + comicname + ' [' + str(volume) + ']</b></center></td></tr><tr><td>'
#filelisting += '<div style="height:300px;overflow:scroll;overflow-x:hidden;">'
filelisting += '<div style="display:inline-block;overflow-y:auto:overflow-x:hidden;">'
cnt = 0
for result in results:
filelisting += result['ComicFilename'] + '</br>'
filelisting += '</div></td></tr>'
filelisting += '<tr><td align="right">' + str(len(results)) + ' Files.</td></tr>'
filelisting += '</table>'
return filelisting
ImportFilelisting.exposed = True
def deleteimport(self, ComicName, volume, DynamicName, Status):
myDB = db.DBConnection()
if volume is None or volume == 'None':
logname = ComicName
else:
logname = ComicName + '[' + str(volume) + ']'
logger.info("Removing import data for Comic: " + logname)
if volume is None or volume == 'None':
myDB.action('DELETE from importresults WHERE DynamicName=? AND Status=? AND (Volume is NULL OR Volume="None")', [DynamicName, Status])
else:
myDB.action('DELETE from importresults WHERE DynamicName=? AND Volume=? AND Status=?', [DynamicName, volume, Status])
raise cherrypy.HTTPRedirect("importResults")
deleteimport.exposed = True
def preSearchit(self, ComicName, comiclist=None, mimp=0, volume=None, displaycomic=None, comicid=None, dynamicname=None, displayline=None):
if mylar.IMPORTLOCK:
logger.info('[IMPORT] There is an import already running. Please wait for it to finish, and then you can resubmit this import.')
return
importlock = threading.Lock()
myDB = db.DBConnection()
if mimp == 0:
comiclist = []
comiclist.append({"ComicName": ComicName,
"DynamicName": dynamicname,
"Volume": volume,
"ComicID": comicid})
with importlock:
#set the global importlock here so that nothing runs and tries to refresh things simultaneously...
mylar.IMPORTLOCK = True
#do imports that have the comicID already present (ie. metatagging has returned valid hits).
#if a comicID is present along with an IssueID - then we have valid metadata.
#otherwise, comicID present by itself indicates a watch match that already exists and is done below this sequence.
RemoveIDS = []
for comicinfo in comiclist:
logger.fdebug('[IMPORT] Checking for any valid ComicID\'s already present within filenames.')
logger.fdebug('[IMPORT] %s:' % comicinfo)
if comicinfo['ComicID'] is None or comicinfo['ComicID'] == 'None':
continue
else:
results = myDB.select("SELECT * FROM importresults WHERE (WatchMatch is Null OR WatchMatch LIKE 'C%') AND ComicID=?", [comicinfo['ComicID']])
files = []
for result in results:
files.append({'comicfilename': result['ComicFilename'],
'comiclocation': result['ComicLocation'],
'issuenumber': result['IssueNumber'],
'import_id': result['impID']})
import random
SRID = str(random.randint(100000, 999999))
logger.info('[IMPORT] Issues found with valid ComicID information for : %s [%s]' % (comicinfo['ComicName'], comicinfo['ComicID']))
imported = {'ComicName': comicinfo['ComicName'],
'DynamicName': comicinfo['DynamicName'],
'Volume': comicinfo['Volume'],
'filelisting': files,
'srid': SRID}
self.addbyid(comicinfo['ComicID'], calledby=True, imported=imported, ogcname=comicinfo['ComicName'], nothread=True)
#if move files wasn't used - we need to update status at this point.
#if mylar.CONFIG.IMP_MOVE is False:
# #status update.
# for f in files:
# ctrlVal = {"ComicID": comicinfo['ComicID'],
# "impID": f['import_id']}
# newVal = {"Status": 'Imported',
# "SRID": SRID,
# "ComicFilename": f['comicfilename'],
# "ComicLocation": f['comiclocation'],
# "Volume": comicinfo['Volume'],
# "IssueNumber": comicinfo['IssueNumber'],
# "ComicName": comicinfo['ComicName'],
# "DynamicName": comicinfo['DynamicName']}
# myDB.upsert("importresults", newVal, ctrlVal)
logger.info('[IMPORT] Successfully verified import sequence data for : %s. Currently adding to your watchlist.' % comicinfo['ComicName'])
RemoveIDS.append(comicinfo['ComicID'])
#we need to remove these items from the comiclist now, so they don't get processed again
if len(RemoveIDS) > 0:
for RID in RemoveIDS:
newlist = [k for k in comiclist if k['ComicID'] != RID]
comiclist = newlist
for cl in comiclist:
ComicName = cl['ComicName']
volume = cl['Volume']
DynamicName = cl['DynamicName']
#logger.fdebug('comicname: ' + ComicName)
#logger.fdebug('dyn: ' + DynamicName)
if volume is None or volume == 'None':
comic_and_vol = ComicName
else:
comic_and_vol = '%s (%s)' % (ComicName, volume)
logger.info('[IMPORT][%s] Now preparing to import. First I need to determine the highest issue, and possible year(s) of the series.' % comic_and_vol)
if volume is None or volume == 'None':
logger.fdebug('[IMPORT] [none] dynamicname: %s' % DynamicName)
logger.fdebug('[IMPORT] [none] volume: None')
results = myDB.select("SELECT * FROM importresults WHERE DynamicName=? AND Volume IS NULL AND Status='Not Imported'", [DynamicName])
else:
logger.fdebug('[IMPORT] [!none] dynamicname: %s' % DynamicName)
logger.fdebug('[IMPORT] [!none] volume: %s' % volume)
results = myDB.select("SELECT * FROM importresults WHERE DynamicName=? AND Volume=? AND Status='Not Imported'", [DynamicName,volume])
if not results:
logger.fdebug('[IMPORT] I cannot find any results for the given series. I should remove this from the list.')
continue
#if results > 0:
# print ("There are " + str(results[7]) + " issues to import of " + str(ComicName))
#build the valid year ranges and the minimum issue# here to pass to search.
yearRANGE = []
yearTOP = 0
minISSUE = 0
startISSUE = 10000000
starttheyear = None
comicstoIMP = []
movealreadyonlist = "no"
movedata = []
for result in results:
if result is None or result == 'None':
logger.info('[IMPORT] Ultron gave me bad information, this issue wont import correctly: %s' & DynamicName)
break
if result['WatchMatch']:
watchmatched = result['WatchMatch']
else:
watchmatched = ''
if watchmatched.startswith('C'):
comicid = result['WatchMatch'][1:]
#since it's already in the watchlist, we just need to move the files and re-run the filechecker.
#self.refreshArtist(comicid=comicid,imported='yes')
if mylar.CONFIG.IMP_MOVE:
comloc = myDB.selectone("SELECT * FROM comics WHERE ComicID=?", [comicid]).fetchone()
movedata_comicid = comicid
movedata_comiclocation = comloc['ComicLocation']
movedata_comicname = ComicName
movealreadyonlist = "yes"
#mylar.moveit.movefiles(comicid,comloc['ComicLocation'],ComicName)
#check for existing files... (this is already called after move files in importer)
#updater.forceRescan(comicid)
else:
raise cherrypy.HTTPRedirect("importResults")
else:
#logger.fdebug('result: %s' % result)
comicstoIMP.append(result['ComicLocation']) #.decode(mylar.SYS_ENCODING, 'replace'))
getiss = result['IssueNumber']
#logger.fdebug('getiss: %s' % getiss)
if 'annual' in getiss.lower():
tmpiss = re.sub('[^0-9]','', getiss).strip()
if any([tmpiss.startswith('19'), tmpiss.startswith('20')]) and len(tmpiss) == 4:
logger.fdebug('[IMPORT] annual detected with no issue [%s]. Skipping this entry for determining series length.' % getiss)
continue
else:
if (result['ComicYear'] not in yearRANGE) or all([yearRANGE is None, yearRANGE == 'None']):
if result['ComicYear'] <> "0000" and result['ComicYear'] is not None:
yearRANGE.append(str(result['ComicYear']))
yearTOP = str(result['ComicYear'])
getiss_num = helpers.issuedigits(getiss)
miniss_num = helpers.issuedigits(minISSUE)
startiss_num = helpers.issuedigits(startISSUE)
if int(getiss_num) > int(miniss_num):
logger.fdebug('Minimum issue now set to : %s - it was %s' % (getiss, minISSUE))
minISSUE = getiss
if int(getiss_num) < int(startiss_num):
logger.fdebug('Start issue now set to : %s - it was %s' % (getiss, startISSUE))
startISSUE = str(getiss)
if helpers.issuedigits(startISSUE) == 1000 and result['ComicYear'] is not None: # if it's an issue #1, get the year and assume that's the start.
startyear = result['ComicYear']
#taking this outside of the transaction in an attempt to stop db locking.
if mylar.CONFIG.IMP_MOVE and movealreadyonlist == "yes":
mylar.moveit.movefiles(movedata_comicid, movedata_comiclocation, movedata_comicname)
updater.forceRescan(comicid)
raise cherrypy.HTTPRedirect("importResults")
#figure out # of issues and the year range allowable
logger.fdebug('[IMPORT] yearTOP: %s' % yearTOP)
logger.fdebug('[IMPORT] yearRANGE: %s' % yearRANGE)
if starttheyear is None:
if all([yearTOP != None, yearTOP != 'None']):
if int(str(yearTOP)) > 0:
minni = helpers.issuedigits(minISSUE)
#logger.info(minni)
if minni < 1 or minni > 999999999:
maxyear = int(str(yearTOP))
else:
maxyear = int(str(yearTOP)) - ( (minni/1000) / 12 )
if str(maxyear) not in yearRANGE:
#logger.info('maxyear:' + str(maxyear))
#logger.info('yeartop:' + str(yearTOP))
for i in range(maxyear, int(yearTOP),1):
if not any(int(x) == int(i) for x in yearRANGE):
yearRANGE.append(str(i))
else:
yearRANGE = None
else:
yearRANGE = None
else:
yearRANGE.append(starttheyear)
if yearRANGE is not None:
yearRANGE = sorted(yearRANGE, reverse=True)
#determine a best-guess to # of issues in series
#this needs to be reworked / refined ALOT more.
#minISSUE = highest issue #, startISSUE = lowest issue #
numissues = len(comicstoIMP)
logger.fdebug('[IMPORT] number of issues: %s' % numissues)
ogcname = ComicName
mode='series'
displaycomic = helpers.filesafe(ComicName)
displaycomic = re.sub('[\-]','', displaycomic).strip()
displaycomic = re.sub('\s+', ' ', displaycomic).strip()
logger.fdebug('[IMPORT] displaycomic : %s' % displaycomic)
logger.fdebug('[IMPORT] comicname : %s' % ComicName)
searchterm = '"' + displaycomic + '"'
try:
if yearRANGE is None:
sresults = mb.findComic(searchterm, mode, issue=numissues) #ogcname, mode, issue=numissues, explicit='all') #ComicName, mode, issue=numissues)
else:
sresults = mb.findComic(searchterm, mode, issue=numissues, limityear=yearRANGE) #ogcname, mode, issue=numissues, limityear=yearRANGE, explicit='all') #ComicName, mode, issue=numissues, limityear=yearRANGE)
except TypeError:
logger.warn('[IMPORT] Comicvine API limit has been reached, and/or the comicvine website is not responding. Aborting process at this time, try again in an ~ hr when the api limit is reset.')
break
else:
if sresults is False:
sresults = []
type='comic'
#we now need to cycle through the results until we get a hit on both dynamicname AND year (~count of issues possibly).
logger.fdebug('[IMPORT] [%s] search results' % len(sresults))
search_matches = []
for results in sresults:
rsn = filechecker.FileChecker()
rsn_run = rsn.dynamic_replace(results['name'])
result_name = rsn_run['mod_seriesname']
result_comicid = results['comicid']
result_year = results['comicyear']
if float(int(results['issues']) / 12):
totalissues = (int(results['issues']) / 12) + 1
else:
totalissues = int(results['issues']) / 12
totalyear_range = int(result_year) + totalissues #2000 + (101 / 12) 2000 +8.4 = 2008
logger.fdebug('[IMPORT] [%s] Comparing: %s - TO - %s' % (totalyear_range, re.sub('[\|\s]', '', DynamicName.lower()).strip(), re.sub('[\|\s]', '', result_name.lower()).strip()))
if any([str(totalyear_range) in results['seriesrange'], result_year in results['seriesrange']]):
logger.fdebug('[IMPORT] LastIssueID: %s' % results['lastissueid'])
if re.sub('[\|\s]', '', DynamicName.lower()).strip() == re.sub('[\|\s]', '', result_name.lower()).strip():
logger.fdebug('[IMPORT MATCH] %s (%s)' % (result_name, result_comicid))
search_matches.append({'comicid': results['comicid'],
'series': results['name'],
'dynamicseries': result_name,
'seriesyear': result_year,
'publisher': results['publisher'],
'haveit': results['haveit'],
'name': results['name'],
'deck': results['deck'],
'url': results['url'],
'description': results['description'],
'comicimage': results['comicimage'],
'issues': results['issues'],
'ogcname': ogcname,
'comicyear': results['comicyear']})
if len(search_matches) == 1:
sr = search_matches[0]
logger.info('[IMPORT] There is only one result...automagik-mode enabled for %s :: %s' % (sr['series'], sr['comicid']))
resultset = 1
else:
if len(search_matches) == 0 or len(search_matches) is None:
logger.fdebug("[IMPORT] no results, removing the year from the agenda and re-querying.")
sresults = mb.findComic(searchterm, mode, issue=numissues) #ComicName, mode, issue=numissues)
logger.fdebug('[IMPORT] [%s] search results' % len(sresults))
for results in sresults:
rsn = filechecker.FileChecker()
rsn_run = rsn.dynamic_replace(results['name'])
result_name = rsn_run['mod_seriesname']
result_comicid = results['comicid']
result_year = results['comicyear']
if float(int(results['issues']) / 12):
totalissues = (int(results['issues']) / 12) + 1
else:
totalissues = int(results['issues']) / 12
totalyear_range = int(result_year) + totalissues #2000 + (101 / 12) 2000 +8.4 = 2008
logger.fdebug('[IMPORT][%s] Comparing: %s - TO - %s' % (totalyear_range, re.sub('[\|\s]', '', DynamicName.lower()).strip(), re.sub('[\|\s]', '', result_name.lower()).strip()))
if any([str(totalyear_range) in results['seriesrange'], result_year in results['seriesrange']]):
if re.sub('[\|\s]', '', DynamicName.lower()).strip() == re.sub('[\|\s]', '', result_name.lower()).strip():
logger.fdebug('[IMPORT MATCH] %s (%s)' % (result_name, result_comicid))
search_matches.append({'comicid': results['comicid'],
'series': results['name'],
'dynamicseries': result_name,
'seriesyear': result_year,
'publisher': results['publisher'],
'haveit': results['haveit'],
'name': results['name'],
'deck': results['deck'],
'url': results['url'],
'description': results['description'],
'comicimage': results['comicimage'],
'issues': results['issues'],
'ogcname': ogcname,
'comicyear': results['comicyear']})
if len(search_matches) == 1:
sr = search_matches[0]
logger.info('[IMPORT] There is only one result...automagik-mode enabled for %s :: %s' % (sr['series'], sr['comicid']))
resultset = 1
else:
resultset = 0
else:
logger.info('[IMPORT] Returning results to Select option - there are %s possibilities, manual intervention required.' % len(search_matches))
resultset = 0
#generate random Search Results ID to allow for easier access for viewing logs / search results.
import random
SRID = str(random.randint(100000, 999999))
#link the SRID to the series that was just imported so that it can reference the search results when requested.
if volume is None or volume == 'None':
ctrlVal = {"DynamicName": DynamicName}
else:
ctrlVal = {"DynamicName": DynamicName,
"Volume": volume}
if len(sresults) > 1 or len(search_matches) > 1:
newVal = {"SRID": SRID,
"Status": 'Manual Intervention',
"ComicName": ComicName}
else:
newVal = {"SRID": SRID,
"Status": 'Importing',
"ComicName": ComicName}
myDB.upsert("importresults", newVal, ctrlVal)
if resultset == 0:
if len(search_matches) > 1:
# if we matched on more than one series above, just save those results instead of the entire search result set.
for sres in search_matches:
if type(sres['haveit']) == dict:
imp_cid = sres['haveit']['comicid']
else:
imp_cid = sres['haveit']
cVal = {"SRID": SRID,
"comicid": sres['comicid']}
#should store ogcname in here somewhere to account for naming conversions above.
nVal = {"Series": ComicName,
"results": len(search_matches),
"publisher": sres['publisher'],
"haveit": imp_cid,
"name": sres['name'],
"deck": sres['deck'],
"url": sres['url'],
"description": sres['description'],
"comicimage": sres['comicimage'],
"issues": sres['issues'],
"ogcname": ogcname,
"comicyear": sres['comicyear']}
#logger.fdebug('search_values: [%s]/%s' % (cVal, nVal))
myDB.upsert("searchresults", nVal, cVal)
logger.info('[IMPORT] There is more than one result that might be valid - normally this is due to the filename(s) not having enough information for me to use (ie. no volume label/year). Manual intervention is required.')
#force the status here just in case
newVal = {'SRID': SRID,
'Status': 'Manual Intervention'}
myDB.upsert("importresults", newVal, ctrlVal)
elif len(sresults) > 1:
# store the search results for series that returned more than one result for user to select later / when they want.
# should probably assign some random numeric for an id to reference back at some point.
for sres in sresults:
if type(sres['haveit']) == dict:
imp_cid = sres['haveit']['comicid']
else:
imp_cid = sres['haveit']
cVal = {"SRID": SRID,
"comicid": sres['comicid']}
#should store ogcname in here somewhere to account for naming conversions above.
nVal = {"Series": ComicName,
"results": len(sresults),
"publisher": sres['publisher'],
"haveit": imp_cid,
"name": sres['name'],
"deck": sres['deck'],
"url": sres['url'],
"description": sres['description'],
"comicimage": sres['comicimage'],
"issues": sres['issues'],
"ogcname": ogcname,
"comicyear": sres['comicyear']}
myDB.upsert("searchresults", nVal, cVal)
logger.info('[IMPORT] There is more than one result that might be valid - normally this is due to the filename(s) not having enough information for me to use (ie. no volume label/year). Manual intervention is required.')
#force the status here just in case
newVal = {'SRID': SRID,
'Status': 'Manual Intervention'}
myDB.upsert("importresults", newVal, ctrlVal)
else:
logger.info('[IMPORT] Could not find any matching results against CV. Check the logs and perhaps rename the attempted file(s)')
newVal = {'SRID': SRID,
'Status': 'No Results'}
myDB.upsert("importresults", newVal, ctrlVal)
else:
logger.info('[IMPORT] Now adding %s...' % ComicName)
if volume is None or volume == 'None':
results = myDB.select("SELECT * FROM importresults WHERE (WatchMatch is Null OR WatchMatch LIKE 'C%') AND DynamicName=? AND Volume IS NULL",[DynamicName])
else:
if not volume.lower().startswith('v'):
volume = 'v' + str(volume)
results = myDB.select("SELECT * FROM importresults WHERE (WatchMatch is Null OR WatchMatch LIKE 'C%') AND DynamicName=? AND Volume=?",[DynamicName,volume])
files = []
for result in results:
files.append({'comicfilename': result['ComicFilename'],
'comiclocation': result['ComicLocation'],
'issuenumber': result['IssueNumber'],
'import_id': result['impID']})
imported = {'ComicName': ComicName,
'DynamicName': DynamicName,
'Volume': volume,
'filelisting': files,
'srid': SRID}
self.addbyid(sr['comicid'], calledby=True, imported=imported, ogcname=ogcname, nothread=True)
mylar.IMPORTLOCK = False
logger.info('[IMPORT] Import completed.')
preSearchit.exposed = True
def importresults_popup(self, SRID, ComicName, imported=None, ogcname=None, DynamicName=None, Volume=None):
myDB = db.DBConnection()
resultset = myDB.select("SELECT * FROM searchresults WHERE SRID=?", [SRID])
if not resultset:
logger.warn('There are no search results to view for this entry ' + ComicName + ' [' + str(SRID) + ']. Something is probably wrong.')
raise cherrypy.HTTPRedirect("importResults")
searchresults = resultset
if any([Volume is None, Volume == 'None']):
results = myDB.select("SELECT * FROM importresults WHERE (WatchMatch is Null OR WatchMatch LIKE 'C%') AND DynamicName=? AND Volume IS NULL",[DynamicName])
else:
if not Volume.lower().startswith('v'):
volume = 'v' + str(Volume)
else:
volume = Volume
results = myDB.select("SELECT * FROM importresults WHERE (WatchMatch is Null OR WatchMatch LIKE 'C%') AND DynamicName=? AND Volume=?",[DynamicName,volume])
files = []
for result in results:
files.append({'comicfilename': result['ComicFilename'],
'comiclocation': result['ComicLocation'],
'issuenumber': result['IssueNumber'],
'import_id': result['impID']})
imported = {'ComicName': ComicName,
'DynamicName': DynamicName,
'Volume': Volume,
'filelisting': files,
'srid': SRID}
return serve_template(templatename="importresults_popup.html", title="results", searchtext=ComicName, searchresults=searchresults, imported=imported)
importresults_popup.exposed = True
def pretty_git(self, br_history):
#in order to 'prettify' the history log for display, we need to break it down so it's line by line.
br_split = br_history.split("\n") #split it on each commit
commit = []
for br in br_split:
commit_st = br.find('-')
commitno = br[:commit_st].strip()
time_end = br.find('-',commit_st+1)
time = br[commit_st+1:time_end].strip()
author_end = br.find('-', time_end+1)
author = br[time_end+1:author_end].strip()
desc = br[author_end+1:].strip()
if len(desc) > 103:
desc = '<span title="%s">%s...</span>' % (desc, desc[:103])
if author != 'evilhero':
pr_tag = True
dspline = '[%s][PR] %s {<span style="font-size:11px">%s/%s</span>}'
else:
pr_tag = False
dspline = '[%s] %s {<span style="font-size:11px">%s/%s</span>}'
commit.append(dspline % ("<a href='https://github.com/evilhero/mylar/commit/" + commitno + "'>"+commitno+"</a>", desc, time, author))
return '<br />\n'.join(commit)
pretty_git.exposed = True
#---
def config(self):
interface_dir = os.path.join(mylar.PROG_DIR, 'data/interfaces/')
interface_list = [name for name in os.listdir(interface_dir) if os.path.isdir(os.path.join(interface_dir, name))]
#----
# to be implemented in the future.
if mylar.INSTALL_TYPE == 'git':
try:
branch_history, err = mylar.versioncheck.runGit('log --encoding=UTF-8 --pretty=format:"%h - %cr - %an - %s" -n 5')
#here we pass the branch_history to the pretty_git module to break it down
if branch_history:
br_hist = self.pretty_git(branch_history)
try:
br_hist = u"" + br_hist.decode('utf-8')
except:
br_hist = br_hist
else:
br_hist = err
except Exception as e:
logger.fdebug('[ERROR] Unable to retrieve git revision history for some reason: %s' % e)
br_hist = 'This would be a nice place to see revision history...'
else:
br_hist = 'This would be a nice place to see revision history...'
#----
myDB = db.DBConnection()
CCOMICS = myDB.select("SELECT COUNT(*) FROM comics")
CHAVES = myDB.select("SELECT COUNT(*) FROM issues WHERE Status='Downloaded' OR Status='Archived'")
CISSUES = myDB.select("SELECT COUNT(*) FROM issues")
CSIZE = myDB.select("select SUM(ComicSize) from issues where Status='Downloaded' or Status='Archived'")
COUNT_COMICS = CCOMICS[0][0]
COUNT_HAVES = CHAVES[0][0]
COUNT_ISSUES = CISSUES[0][0]
COUNT_SIZE = helpers.human_size(CSIZE[0][0])
CCONTCOUNT = 0
cti = helpers.havetotals()
for cchk in cti:
if cchk['recentstatus'] is 'Continuing':
CCONTCOUNT += 1
comicinfo = {"COUNT_COMICS": COUNT_COMICS,
"COUNT_HAVES": COUNT_HAVES,
"COUNT_ISSUES": COUNT_ISSUES,
"COUNT_SIZE": COUNT_SIZE,
"CCONTCOUNT": CCONTCOUNT}
DLPROVSTATS = myDB.select("SELECT Provider, COUNT(Provider) AS Frequency FROM Snatched WHERE Status = 'Snatched' AND Provider is NOT NULL GROUP BY Provider ORDER BY Frequency DESC")
freq = dict()
freq_tot = 0
for row in DLPROVSTATS:
if any(['CBT' in row['Provider'], '32P' in row['Provider'], 'ComicBT' in row['Provider']]):
try:
tmpval = freq['32P']
freq.update({'32P': tmpval + row['Frequency']})
except:
freq.update({'32P': row['Frequency']})
elif 'KAT' in row['Provider']:
try:
tmpval = freq['KAT']
freq.update({'KAT': tmpval + row['Frequency']})
except:
freq.update({'KAT': row['Frequency']})
elif 'experimental' in row['Provider']:
try:
tmpval = freq['Experimental']
freq.update({'Experimental': tmpval + row['Frequency']})
except:
freq.update({'Experimental': row['Frequency']})
elif [True for x in freq if re.sub("\(newznab\)", "", str(row['Provider'])).strip() in x]:
try:
tmpval = freq[re.sub("\(newznab\)", "", row['Provider']).strip()]
freq.update({re.sub("\(newznab\)", "", row['Provider']).strip(): tmpval + row['Frequency']})
except:
freq.update({re.sub("\(newznab\)", "", row['Provider']).strip(): row['Frequency']})
else:
freq.update({re.sub("\(newznab\)", "", row['Provider']).strip(): row['Frequency']})
freq_tot += row['Frequency']
dlprovstats = sorted(freq.iteritems(), key=itemgetter(1), reverse=True)
if mylar.SCHED_RSS_LAST is None:
rss_sclast = 'Unknown'
else:
rss_sclast = datetime.datetime.fromtimestamp(mylar.SCHED_RSS_LAST).replace(microsecond=0)
config = {
"comicvine_api": mylar.CONFIG.COMICVINE_API,
"http_host": mylar.CONFIG.HTTP_HOST,
"http_user": mylar.CONFIG.HTTP_USERNAME,
"http_port": mylar.CONFIG.HTTP_PORT,
"http_pass": mylar.CONFIG.HTTP_PASSWORD,
"enable_https": helpers.checked(mylar.CONFIG.ENABLE_HTTPS),
"https_cert": mylar.CONFIG.HTTPS_CERT,
"https_key": mylar.CONFIG.HTTPS_KEY,
"authentication": int(mylar.CONFIG.AUTHENTICATION),
"api_enabled": helpers.checked(mylar.CONFIG.API_ENABLED),
"api_key": mylar.CONFIG.API_KEY,
"launch_browser": helpers.checked(mylar.CONFIG.LAUNCH_BROWSER),
"auto_update": helpers.checked(mylar.CONFIG.AUTO_UPDATE),
"max_logsize": mylar.CONFIG.MAX_LOGSIZE,
"annuals_on": helpers.checked(mylar.CONFIG.ANNUALS_ON),
"enable_check_folder": helpers.checked(mylar.CONFIG.ENABLE_CHECK_FOLDER),
"check_folder": mylar.CONFIG.CHECK_FOLDER,
"download_scan_interval": mylar.CONFIG.DOWNLOAD_SCAN_INTERVAL,
"search_interval": mylar.CONFIG.SEARCH_INTERVAL,
"nzb_startup_search": helpers.checked(mylar.CONFIG.NZB_STARTUP_SEARCH),
"search_delay": mylar.CONFIG.SEARCH_DELAY,
"nzb_downloader_sabnzbd": helpers.radio(mylar.CONFIG.NZB_DOWNLOADER, 0),
"nzb_downloader_nzbget": helpers.radio(mylar.CONFIG.NZB_DOWNLOADER, 1),
"nzb_downloader_blackhole": helpers.radio(mylar.CONFIG.NZB_DOWNLOADER, 2),
"sab_host": mylar.CONFIG.SAB_HOST,
"sab_user": mylar.CONFIG.SAB_USERNAME,
"sab_api": mylar.CONFIG.SAB_APIKEY,
"sab_pass": mylar.CONFIG.SAB_PASSWORD,
"sab_cat": mylar.CONFIG.SAB_CATEGORY,
"sab_priority": mylar.CONFIG.SAB_PRIORITY,
"sab_directory": mylar.CONFIG.SAB_DIRECTORY,
"sab_to_mylar": helpers.checked(mylar.CONFIG.SAB_TO_MYLAR),
"sab_version": mylar.CONFIG.SAB_VERSION,
"sab_client_post_processing": helpers.checked(mylar.CONFIG.SAB_CLIENT_POST_PROCESSING),
"nzbget_host": mylar.CONFIG.NZBGET_HOST,
"nzbget_port": mylar.CONFIG.NZBGET_PORT,
"nzbget_user": mylar.CONFIG.NZBGET_USERNAME,
"nzbget_pass": mylar.CONFIG.NZBGET_PASSWORD,
"nzbget_cat": mylar.CONFIG.NZBGET_CATEGORY,
"nzbget_priority": mylar.CONFIG.NZBGET_PRIORITY,
"nzbget_directory": mylar.CONFIG.NZBGET_DIRECTORY,
"nzbget_client_post_processing": helpers.checked(mylar.CONFIG.NZBGET_CLIENT_POST_PROCESSING),
"torrent_downloader_watchlist": helpers.radio(int(mylar.CONFIG.TORRENT_DOWNLOADER), 0),
"torrent_downloader_utorrent": helpers.radio(int(mylar.CONFIG.TORRENT_DOWNLOADER), 1),
"torrent_downloader_rtorrent": helpers.radio(int(mylar.CONFIG.TORRENT_DOWNLOADER), 2),
"torrent_downloader_transmission": helpers.radio(int(mylar.CONFIG.TORRENT_DOWNLOADER), 3),
"torrent_downloader_deluge": helpers.radio(int(mylar.CONFIG.TORRENT_DOWNLOADER), 4),
"torrent_downloader_qbittorrent": helpers.radio(int(mylar.CONFIG.TORRENT_DOWNLOADER), 5),
"utorrent_host": mylar.CONFIG.UTORRENT_HOST,
"utorrent_username": mylar.CONFIG.UTORRENT_USERNAME,
"utorrent_password": mylar.CONFIG.UTORRENT_PASSWORD,
"utorrent_label": mylar.CONFIG.UTORRENT_LABEL,
"rtorrent_host": mylar.CONFIG.RTORRENT_HOST,
"rtorrent_rpc_url": mylar.CONFIG.RTORRENT_RPC_URL,
"rtorrent_authentication": mylar.CONFIG.RTORRENT_AUTHENTICATION,
"rtorrent_ssl": helpers.checked(mylar.CONFIG.RTORRENT_SSL),
"rtorrent_verify": helpers.checked(mylar.CONFIG.RTORRENT_VERIFY),
"rtorrent_username": mylar.CONFIG.RTORRENT_USERNAME,
"rtorrent_password": mylar.CONFIG.RTORRENT_PASSWORD,
"rtorrent_directory": mylar.CONFIG.RTORRENT_DIRECTORY,
"rtorrent_label": mylar.CONFIG.RTORRENT_LABEL,
"rtorrent_startonload": helpers.checked(mylar.CONFIG.RTORRENT_STARTONLOAD),
"transmission_host": mylar.CONFIG.TRANSMISSION_HOST,
"transmission_username": mylar.CONFIG.TRANSMISSION_USERNAME,
"transmission_password": mylar.CONFIG.TRANSMISSION_PASSWORD,
"transmission_directory": mylar.CONFIG.TRANSMISSION_DIRECTORY,
"deluge_host": mylar.CONFIG.DELUGE_HOST,
"deluge_username": mylar.CONFIG.DELUGE_USERNAME,
"deluge_password": mylar.CONFIG.DELUGE_PASSWORD,
"deluge_label": mylar.CONFIG.DELUGE_LABEL,
"deluge_pause": helpers.checked(mylar.CONFIG.DELUGE_PAUSE),
"deluge_download_directory": mylar.CONFIG.DELUGE_DOWNLOAD_DIRECTORY,
"deluge_done_directory": mylar.CONFIG.DELUGE_DONE_DIRECTORY,
"qbittorrent_host": mylar.CONFIG.QBITTORRENT_HOST,
"qbittorrent_username": mylar.CONFIG.QBITTORRENT_USERNAME,
"qbittorrent_password": mylar.CONFIG.QBITTORRENT_PASSWORD,
"qbittorrent_label": mylar.CONFIG.QBITTORRENT_LABEL,
"qbittorrent_folder": mylar.CONFIG.QBITTORRENT_FOLDER,
"qbittorrent_loadaction": mylar.CONFIG.QBITTORRENT_LOADACTION,
"blackhole_dir": mylar.CONFIG.BLACKHOLE_DIR,
"usenet_retention": mylar.CONFIG.USENET_RETENTION,
"nzbsu": helpers.checked(mylar.CONFIG.NZBSU),
"nzbsu_uid": mylar.CONFIG.NZBSU_UID,
"nzbsu_api": mylar.CONFIG.NZBSU_APIKEY,
"nzbsu_verify": helpers.checked(mylar.CONFIG.NZBSU_VERIFY),
"dognzb": helpers.checked(mylar.CONFIG.DOGNZB),
"dognzb_api": mylar.CONFIG.DOGNZB_APIKEY,
"dognzb_verify": helpers.checked(mylar.CONFIG.DOGNZB_VERIFY),
"experimental": helpers.checked(mylar.CONFIG.EXPERIMENTAL),
"enable_torznab": helpers.checked(mylar.CONFIG.ENABLE_TORZNAB),
"extra_torznabs": sorted(mylar.CONFIG.EXTRA_TORZNABS, key=itemgetter(5), reverse=True),
"newznab": helpers.checked(mylar.CONFIG.NEWZNAB),
"extra_newznabs": sorted(mylar.CONFIG.EXTRA_NEWZNABS, key=itemgetter(5), reverse=True),
"enable_ddl": helpers.checked(mylar.CONFIG.ENABLE_DDL),
"enable_rss": helpers.checked(mylar.CONFIG.ENABLE_RSS),
"rss_checkinterval": mylar.CONFIG.RSS_CHECKINTERVAL,
"rss_last": rss_sclast,
"provider_order": mylar.CONFIG.PROVIDER_ORDER,
"enable_torrents": helpers.checked(mylar.CONFIG.ENABLE_TORRENTS),
"minseeds": mylar.CONFIG.MINSEEDS,
"torrent_local": helpers.checked(mylar.CONFIG.TORRENT_LOCAL),
"local_watchdir": mylar.CONFIG.LOCAL_WATCHDIR,
"torrent_seedbox": helpers.checked(mylar.CONFIG.TORRENT_SEEDBOX),
"seedbox_watchdir": mylar.CONFIG.SEEDBOX_WATCHDIR,
"seedbox_host": mylar.CONFIG.SEEDBOX_HOST,
"seedbox_port": mylar.CONFIG.SEEDBOX_PORT,
"seedbox_user": mylar.CONFIG.SEEDBOX_USER,
"seedbox_pass": mylar.CONFIG.SEEDBOX_PASS,
"enable_torrent_search": helpers.checked(mylar.CONFIG.ENABLE_TORRENT_SEARCH),
"enable_public": helpers.checked(mylar.CONFIG.ENABLE_PUBLIC),
"enable_32p": helpers.checked(mylar.CONFIG.ENABLE_32P),
"legacymode_32p": helpers.radio(mylar.CONFIG.MODE_32P, 0),
"authmode_32p": helpers.radio(mylar.CONFIG.MODE_32P, 1),
"rssfeed_32p": mylar.CONFIG.RSSFEED_32P,
"passkey_32p": mylar.CONFIG.PASSKEY_32P,
"username_32p": mylar.CONFIG.USERNAME_32P,
"password_32p": mylar.CONFIG.PASSWORD_32P,
"snatchedtorrent_notify": helpers.checked(mylar.CONFIG.SNATCHEDTORRENT_NOTIFY),
"destination_dir": mylar.CONFIG.DESTINATION_DIR,
"create_folders": helpers.checked(mylar.CONFIG.CREATE_FOLDERS),
"enforce_perms": helpers.checked(mylar.CONFIG.ENFORCE_PERMS),
"chmod_dir": mylar.CONFIG.CHMOD_DIR,
"chmod_file": mylar.CONFIG.CHMOD_FILE,
"chowner": mylar.CONFIG.CHOWNER,
"chgroup": mylar.CONFIG.CHGROUP,
"replace_spaces": helpers.checked(mylar.CONFIG.REPLACE_SPACES),
"replace_char": mylar.CONFIG.REPLACE_CHAR,
"use_minsize": helpers.checked(mylar.CONFIG.USE_MINSIZE),
"minsize": mylar.CONFIG.MINSIZE,
"use_maxsize": helpers.checked(mylar.CONFIG.USE_MAXSIZE),
"maxsize": mylar.CONFIG.MAXSIZE,
"interface_list": interface_list,
"dupeconstraint": mylar.CONFIG.DUPECONSTRAINT,
"ddump": helpers.checked(mylar.CONFIG.DDUMP),
"duplicate_dump": mylar.CONFIG.DUPLICATE_DUMP,
"autowant_all": helpers.checked(mylar.CONFIG.AUTOWANT_ALL),
"autowant_upcoming": helpers.checked(mylar.CONFIG.AUTOWANT_UPCOMING),
"comic_cover_local": helpers.checked(mylar.CONFIG.COMIC_COVER_LOCAL),
"alternate_latest_series_covers": helpers.checked(mylar.CONFIG.ALTERNATE_LATEST_SERIES_COVERS),
"pref_qual_0": helpers.radio(int(mylar.CONFIG.PREFERRED_QUALITY), 0),
"pref_qual_1": helpers.radio(int(mylar.CONFIG.PREFERRED_QUALITY), 1),
"pref_qual_2": helpers.radio(int(mylar.CONFIG.PREFERRED_QUALITY), 2),
"move_files": helpers.checked(mylar.CONFIG.MOVE_FILES),
"rename_files": helpers.checked(mylar.CONFIG.RENAME_FILES),
"folder_format": mylar.CONFIG.FOLDER_FORMAT,
"file_format": mylar.CONFIG.FILE_FORMAT,
"zero_level": helpers.checked(mylar.CONFIG.ZERO_LEVEL),
"zero_level_n": mylar.CONFIG.ZERO_LEVEL_N,
"add_to_csv": helpers.checked(mylar.CONFIG.ADD_TO_CSV),
"cvinfo": helpers.checked(mylar.CONFIG.CVINFO),
"lowercase_filenames": helpers.checked(mylar.CONFIG.LOWERCASE_FILENAMES),
"syno_fix": helpers.checked(mylar.CONFIG.SYNO_FIX),
"prowl_enabled": helpers.checked(mylar.CONFIG.PROWL_ENABLED),
"prowl_onsnatch": helpers.checked(mylar.CONFIG.PROWL_ONSNATCH),
"prowl_keys": mylar.CONFIG.PROWL_KEYS,
"prowl_priority": mylar.CONFIG.PROWL_PRIORITY,
"pushover_enabled": helpers.checked(mylar.CONFIG.PUSHOVER_ENABLED),
"pushover_onsnatch": helpers.checked(mylar.CONFIG.PUSHOVER_ONSNATCH),
"pushover_apikey": mylar.CONFIG.PUSHOVER_APIKEY,
"pushover_userkey": mylar.CONFIG.PUSHOVER_USERKEY,
"pushover_device": mylar.CONFIG.PUSHOVER_DEVICE,
"pushover_priority": mylar.CONFIG.PUSHOVER_PRIORITY,
"boxcar_enabled": helpers.checked(mylar.CONFIG.BOXCAR_ENABLED),
"boxcar_onsnatch": helpers.checked(mylar.CONFIG.BOXCAR_ONSNATCH),
"boxcar_token": mylar.CONFIG.BOXCAR_TOKEN,
"pushbullet_enabled": helpers.checked(mylar.CONFIG.PUSHBULLET_ENABLED),
"pushbullet_onsnatch": helpers.checked(mylar.CONFIG.PUSHBULLET_ONSNATCH),
"pushbullet_apikey": mylar.CONFIG.PUSHBULLET_APIKEY,
"pushbullet_deviceid": mylar.CONFIG.PUSHBULLET_DEVICEID,
"pushbullet_channel_tag": mylar.CONFIG.PUSHBULLET_CHANNEL_TAG,
"telegram_enabled": helpers.checked(mylar.CONFIG.TELEGRAM_ENABLED),
"telegram_onsnatch": helpers.checked(mylar.CONFIG.TELEGRAM_ONSNATCH),
"telegram_token": mylar.CONFIG.TELEGRAM_TOKEN,
"telegram_userid": mylar.CONFIG.TELEGRAM_USERID,
"slack_enabled": helpers.checked(mylar.CONFIG.SLACK_ENABLED),
"slack_webhook_url": mylar.CONFIG.SLACK_WEBHOOK_URL,
"slack_onsnatch": helpers.checked(mylar.CONFIG.SLACK_ONSNATCH),
"email_enabled": helpers.checked(mylar.CONFIG.EMAIL_ENABLED),
"email_from": mylar.CONFIG.EMAIL_FROM,
"email_to": mylar.CONFIG.EMAIL_TO,
"email_server": mylar.CONFIG.EMAIL_SERVER,
"email_user": mylar.CONFIG.EMAIL_USER,
"email_password": mylar.CONFIG.EMAIL_PASSWORD,
"email_port": int(mylar.CONFIG.EMAIL_PORT),
"email_raw": helpers.radio(int(mylar.CONFIG.EMAIL_ENC), 0),
"email_ssl": helpers.radio(int(mylar.CONFIG.EMAIL_ENC), 1),
"email_tls": helpers.radio(int(mylar.CONFIG.EMAIL_ENC), 2),
"email_ongrab": helpers.checked(mylar.CONFIG.EMAIL_ONGRAB),
"email_onpost": helpers.checked(mylar.CONFIG.EMAIL_ONPOST),
"enable_extra_scripts": helpers.checked(mylar.CONFIG.ENABLE_EXTRA_SCRIPTS),
"extra_scripts": mylar.CONFIG.EXTRA_SCRIPTS,
"enable_snatch_script": helpers.checked(mylar.CONFIG.ENABLE_SNATCH_SCRIPT),
"snatch_script": mylar.CONFIG.SNATCH_SCRIPT,
"enable_pre_scripts": helpers.checked(mylar.CONFIG.ENABLE_PRE_SCRIPTS),
"pre_scripts": mylar.CONFIG.PRE_SCRIPTS,
"post_processing": helpers.checked(mylar.CONFIG.POST_PROCESSING),
"file_opts": mylar.CONFIG.FILE_OPTS,
"enable_meta": helpers.checked(mylar.CONFIG.ENABLE_META),
"cbr2cbz_only": helpers.checked(mylar.CONFIG.CBR2CBZ_ONLY),
"cmtagger_path": mylar.CONFIG.CMTAGGER_PATH,
"ct_tag_cr": helpers.checked(mylar.CONFIG.CT_TAG_CR),
"ct_tag_cbl": helpers.checked(mylar.CONFIG.CT_TAG_CBL),
"ct_cbz_overwrite": helpers.checked(mylar.CONFIG.CT_CBZ_OVERWRITE),
"unrar_cmd": mylar.CONFIG.UNRAR_CMD,
"failed_download_handling": helpers.checked(mylar.CONFIG.FAILED_DOWNLOAD_HANDLING),
"failed_auto": helpers.checked(mylar.CONFIG.FAILED_AUTO),
"branch": mylar.CONFIG.GIT_BRANCH,
"br_type": mylar.INSTALL_TYPE,
"br_version": mylar.versioncheck.getVersion()[0],
"py_version": platform.python_version(),
"data_dir": mylar.DATA_DIR,
"prog_dir": mylar.PROG_DIR,
"cache_dir": mylar.CONFIG.CACHE_DIR,
"config_file": mylar.CONFIG_FILE,
"lang": '%s.%s' % (logger.LOG_LANG,logger.LOG_CHARSET),
"branch_history" : br_hist,
"log_dir": mylar.CONFIG.LOG_DIR,
"opds_enable": helpers.checked(mylar.CONFIG.OPDS_ENABLE),
"opds_authentication": helpers.checked(mylar.CONFIG.OPDS_AUTHENTICATION),
"opds_username": mylar.CONFIG.OPDS_USERNAME,
"opds_password": mylar.CONFIG.OPDS_PASSWORD,
"opds_metainfo": helpers.checked(mylar.CONFIG.OPDS_METAINFO),
"opds_pagesize": mylar.CONFIG.OPDS_PAGESIZE,
"dlstats": dlprovstats,
"dltotals": freq_tot,
"alphaindex": mylar.CONFIG.ALPHAINDEX
}
return serve_template(templatename="config.html", title="Settings", config=config, comicinfo=comicinfo)
config.exposed = True
def error_change(self, comicid, errorgcd, comicname, comicyear, imported=None, mogcname=None):
# if comicname contains a "," it will break the exceptions import.
import urllib
b = urllib.unquote_plus(comicname)
# cname = b.decode("utf-8")
cname = b.encode('utf-8')
cname = re.sub("\,", "", cname)
if mogcname != None:
c = urllib.unquote_plus(mogcname)
ogcname = c.encode('utf-8')
else:
ogcname = None
if errorgcd[:5].isdigit():
logger.info("GCD-ID detected : " + str(errorgcd)[:5])
logger.info("ogcname: " + str(ogcname))
logger.info("I'm assuming you know what you're doing - going to force-match for " + cname)
self.from_Exceptions(comicid=comicid, gcdid=errorgcd, comicname=cname, comicyear=comicyear, imported=imported, ogcname=ogcname)
else:
logger.info("Assuming rewording of Comic - adjusting to : " + str(errorgcd))
Err_Info = mylar.cv.getComic(comicid, 'comic')
self.addComic(comicid=comicid, comicname=str(errorgcd), comicyear=Err_Info['ComicYear'], comicissues=Err_Info['ComicIssues'], comicpublisher=Err_Info['ComicPublisher'])
error_change.exposed = True
def manual_annual_add(self, manual_comicid, comicname, comicyear, comicid, x=None, y=None):
import urllib
b = urllib.unquote_plus(comicname)
cname = b.encode('utf-8')
logger.fdebug('comicid to be attached : ' + str(manual_comicid))
logger.fdebug('comicname : ' + str(cname))
logger.fdebug('comicyear : ' + str(comicyear))
logger.fdebug('comicid : ' + str(comicid))
issueid = manual_comicid
logger.fdebug('I will be adding ' + str(issueid) + ' to the Annual list for this series.')
threading.Thread(target=importer.manualAnnual, args=[manual_comicid, cname, comicyear, comicid]).start()
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % comicid)
manual_annual_add.exposed = True
def comic_config(self, com_location, ComicID, alt_search=None, fuzzy_year=None, comic_version=None, force_continuing=None, force_type=None, alt_filename=None, allow_packs=None, corrected_seriesyear=None, torrentid_32p=None):
myDB = db.DBConnection()
chk1 = myDB.selectone('SELECT ComicLocation, Corrected_Type FROM comics WHERE ComicID=?', [ComicID]).fetchone()
if chk1[0] is None:
orig_location = com_location
else:
orig_location = chk1[0]
if chk1[1] is None:
orig_type = None
else:
orig_type = chk1[1]
#--- this is for multiple search terms............
#--- works, just need to redo search.py to accomodate multiple search terms
ffs_alt = []
if '##' in alt_search:
ffs = alt_search.find('##')
ffs_alt.append(alt_search[:ffs])
ffs_alt_st = str(ffs_alt[0])
ffs_test = alt_search.split('##')
if len(ffs_test) > 0:
ffs_count = len(ffs_test)
n=1
while (n < ffs_count):
ffs_alt.append(ffs_test[n])
ffs_alt_st = str(ffs_alt_st) + "..." + str(ffs_test[n])
n+=1
asearch = ffs_alt
else:
asearch = alt_search
asearch = str(alt_search)
controlValueDict = {'ComicID': ComicID}
newValues = {}
if asearch is not None:
if re.sub(r'\s', '', asearch) == '':
newValues['AlternateSearch'] = "None"
else:
newValues['AlternateSearch'] = str(asearch)
else:
newValues['AlternateSearch'] = "None"
if fuzzy_year is None:
newValues['UseFuzzy'] = "0"
else:
newValues['UseFuzzy'] = str(fuzzy_year)
if corrected_seriesyear is not None:
newValues['Corrected_SeriesYear'] = str(corrected_seriesyear)
newValues['ComicYear'] = str(corrected_seriesyear)
if comic_version is None or comic_version == 'None':
newValues['ComicVersion'] = "None"
else:
if comic_version[1:].isdigit() and comic_version[:1].lower() == 'v':
newValues['ComicVersion'] = str(comic_version)
else:
logger.info("Invalid Versioning entered - it must be in the format of v#")
newValues['ComicVersion'] = "None"
if force_continuing is None:
newValues['ForceContinuing'] = 0
else:
newValues['ForceContinuing'] = 1
if force_type == '1':
newValues['Corrected_Type'] = 'TPB'
elif force_type == '2':
newValues['Corrected_Type'] = 'Print'
else:
newValues['Corrected_Type'] = None
if orig_type != force_type:
if '$Type' in mylar.CONFIG.FOLDER_FORMAT and com_location == orig_location:
#rename folder to accomodate new forced TPB format.
import filers
x = filers.FileHandlers(ComicID=ComicID)
newcom_location = x.folder_create(booktype=newValues['Corrected_Type'])
if newcom_location is not None:
com_location = newcom_location
if allow_packs is None:
newValues['AllowPacks'] = 0
else:
newValues['AllowPacks'] = 1
newValues['TorrentID_32P'] = torrentid_32p
if alt_filename is None or alt_filename == 'None':
newValues['AlternateFileName'] = "None"
else:
newValues['AlternateFileName'] = str(alt_filename)
#force the check/creation of directory com_location here
updatedir = True
if any([mylar.CONFIG.CREATE_FOLDERS is True, os.path.isdir(orig_location)]):
if os.path.isdir(str(com_location)):
logger.info(u"Validating Directory (" + str(com_location) + "). Already exists! Continuing...")
else:
if orig_location != com_location and os.path.isdir(orig_location) is True:
logger.fdebug('Renaming existing location [%s] to new location: %s' % (orig_location, com_location))
try:
os.rename(orig_location, com_location)
except Exception as e:
if 'No such file or directory' in e:
checkdirectory = filechecker.validateAndCreateDirectory(com_location, True)
if not checkdirectory:
logger.warn('Error trying to validate/create directory. Aborting this process at this time.')
updatedir = False
else:
logger.warn('Unable to rename existing directory: %s' % e)
updatedir = False
else:
if orig_location != com_location and os.path.isdir(orig_location) is False:
logger.fdebug("Original Directory (%s) doesn't exist! - attempting to create new directory (%s)" % (orig_location, com_location))
else:
logger.fdebug("Updated Directory doesn't exist! - attempting to create now.")
checkdirectory = filechecker.validateAndCreateDirectory(com_location, True)
if not checkdirectory:
logger.warn('Error trying to validate/create directory. Aborting this process at this time.')
updatedir = False
else:
logger.info('[Create directories False] Not creating physical directory, but updating series location in dB to: %s' % com_location)
if updatedir is True:
newValues['ComicLocation'] = com_location
myDB.upsert("comics", newValues, controlValueDict)
logger.fdebug('Updated Series options!')
raise cherrypy.HTTPRedirect("comicDetails?ComicID=%s" % ComicID)
comic_config.exposed = True
def readlistOptions(self, send2read=0, tab_enable=0, tab_host=None, tab_user=None, tab_pass=None, tab_directory=None, maintainseriesfolder=0):
mylar.CONFIG.SEND2READ = bool(int(send2read))
mylar.CONFIG.MAINTAINSERIESFOLDER = bool(int(maintainseriesfolder))
mylar.CONFIG.TAB_ENABLE = bool(int(tab_enable))
mylar.CONFIG.TAB_HOST = tab_host
mylar.CONFIG.TAB_USER = tab_user
mylar.CONFIG.TAB_PASS = tab_pass
mylar.CONFIG.TAB_DIRECTORY = tab_directory
readoptions = {'send2read': mylar.CONFIG.SEND2READ,
'maintainseriesfolder': mylar.CONFIG.MAINTAINSERIESFOLDER,
'tab_enable': mylar.CONFIG.TAB_ENABLE,
'tab_host': mylar.CONFIG.TAB_HOST,
'tab_user': mylar.CONFIG.TAB_USER,
'tab_pass': mylar.CONFIG.TAB_PASS,
'tab_directory': mylar.CONFIG.TAB_DIRECTORY}
mylar.CONFIG.writeconfig(values=readoptions)
raise cherrypy.HTTPRedirect("readlist")
readlistOptions.exposed = True
def arcOptions(self, StoryArcID=None, StoryArcName=None, read2filename=0, storyarcdir=0, arc_folderformat=None, copy2arcdir=0, arc_fileops='copy'):
mylar.CONFIG.READ2FILENAME = bool(int(read2filename))
mylar.CONFIG.STORYARCDIR = bool(int(storyarcdir))
if arc_folderformat is None:
mylar.CONFIG.ARC_FOLDERFORMAT = "($arc) ($spanyears)"
else:
mylar.CONFIG.ARC_FOLDERFORMAT = arc_folderformat
mylar.CONFIG.COPY2ARCDIR = bool(int(copy2arcdir))
mylar.CONFIG.ARC_FILEOPS = arc_fileops
options = {'read2filename': mylar.CONFIG.READ2FILENAME,
'storyarcdir': mylar.CONFIG.STORYARCDIR,
'arc_folderformat': mylar.CONFIG.ARC_FOLDERFORMAT,
'copy2arcdir': mylar.CONFIG.COPY2ARCDIR,
'arc_fileops': mylar.CONFIG.ARC_FILEOPS}
mylar.CONFIG.writeconfig(values=options)
#force the check/creation of directory com_location here
if mylar.CONFIG.STORYARCDIR is True:
arcdir = os.path.join(mylar.CONFIG.DESTINATION_DIR, 'StoryArcs')
if os.path.isdir(arcdir):
logger.info('Validating Directory (%s). Already exists! Continuing...' % arcdir)
else:
logger.fdebug('Storyarc Directory doesn\'t exist! Attempting to create now.')
checkdirectory = filechecker.validateAndCreateDirectory(arcdir, True)
if not checkdirectory:
logger.warn('Error trying to validate/create directory. Aborting this process at this time.')
return
if StoryArcID is not None:
raise cherrypy.HTTPRedirect("detailStoryArc?StoryArcID=%s&StoryArcName=%s" % (StoryArcID, StoryArcName))
else:
raise cherrypy.HTTPRedirect("storyarc_main")
arcOptions.exposed = True
def configUpdate(self, **kwargs):
checked_configs = ['enable_https', 'launch_browser', 'syno_fix', 'auto_update', 'annuals_on', 'api_enabled', 'nzb_startup_search',
'enforce_perms', 'sab_to_mylar', 'torrent_local', 'torrent_seedbox', 'rtorrent_ssl', 'rtorrent_verify', 'rtorrent_startonload',
'enable_torrents', 'enable_rss', 'nzbsu', 'nzbsu_verify',
'dognzb', 'dognzb_verify', 'experimental', 'enable_torrent_search', 'enable_32p', 'enable_torznab',
'newznab', 'use_minsize', 'use_maxsize', 'ddump', 'failed_download_handling', 'sab_client_post_processing', 'nzbget_client_post_processing',
'failed_auto', 'post_processing', 'enable_check_folder', 'enable_pre_scripts', 'enable_snatch_script', 'enable_extra_scripts',
'enable_meta', 'cbr2cbz_only', 'ct_tag_cr', 'ct_tag_cbl', 'ct_cbz_overwrite', 'rename_files', 'replace_spaces', 'zero_level',
'lowercase_filenames', 'autowant_upcoming', 'autowant_all', 'comic_cover_local', 'alternate_latest_series_covers', 'cvinfo', 'snatchedtorrent_notify',
'prowl_enabled', 'prowl_onsnatch', 'pushover_enabled', 'pushover_onsnatch', 'boxcar_enabled',
'boxcar_onsnatch', 'pushbullet_enabled', 'pushbullet_onsnatch', 'telegram_enabled', 'telegram_onsnatch', 'slack_enabled', 'slack_onsnatch',
'email_enabled', 'email_enc', 'email_ongrab', 'email_onpost', 'opds_enable', 'opds_authentication', 'opds_metainfo', 'opds_pagesize', 'enable_ddl', 'deluge_pause'] #enable_public
for checked_config in checked_configs:
if checked_config not in kwargs:
kwargs[checked_config] = False
for k, v in kwargs.iteritems():
try:
_conf = mylar.CONFIG._define(k)
except KeyError:
continue
mylar.CONFIG.EXTRA_NEWZNABS = []
for kwarg in [x for x in kwargs if x.startswith('newznab_name')]:
if kwarg.startswith('newznab_name'):
newznab_number = kwarg[12:]
newznab_name = kwargs['newznab_name' + newznab_number]
if newznab_name == "":
newznab_name = kwargs['newznab_host' + newznab_number]
if newznab_name == "":
continue
newznab_host = helpers.clean_url(kwargs['newznab_host' + newznab_number])
try:
newznab_verify = kwargs['newznab_verify' + newznab_number]
except:
newznab_verify = 0
newznab_api = kwargs['newznab_api' + newznab_number]
newznab_uid = kwargs['newznab_uid' + newznab_number]
try:
newznab_enabled = str(kwargs['newznab_enabled' + newznab_number])
except KeyError:
newznab_enabled = '0'
del kwargs[kwarg]
mylar.CONFIG.EXTRA_NEWZNABS.append((newznab_name, newznab_host, newznab_verify, newznab_api, newznab_uid, newznab_enabled))
mylar.CONFIG.EXTRA_TORZNABS = []
for kwarg in [x for x in kwargs if x.startswith('torznab_name')]:
if kwarg.startswith('torznab_name'):
torznab_number = kwarg[12:]
torznab_name = kwargs['torznab_name' + torznab_number]
if torznab_name == "":
torznab_name = kwargs['torznab_host' + torznab_number]
if torznab_name == "":
continue
torznab_host = helpers.clean_url(kwargs['torznab_host' + torznab_number])
try:
torznab_verify = kwargs['torznab_verify' + torznab_number]
except:
torznab_verify = 0
torznab_api = kwargs['torznab_apikey' + torznab_number]
torznab_category = kwargs['torznab_category' + torznab_number]
try:
torznab_enabled = str(kwargs['torznab_enabled' + torznab_number])
except KeyError:
torznab_enabled = '0'
del kwargs[kwarg]
mylar.CONFIG.EXTRA_TORZNABS.append((torznab_name, torznab_host, torznab_verify, torznab_api, torznab_category, torznab_enabled))
mylar.CONFIG.process_kwargs(kwargs)
#this makes sure things are set to the default values if they're not appropriately set.
mylar.CONFIG.configure(update=True, startup=False)
# Write the config
logger.info('Now saving config...')
mylar.CONFIG.writeconfig()
configUpdate.exposed = True
def SABtest(self, sabhost=None, sabusername=None, sabpassword=None, sabapikey=None):
if sabhost is None:
sabhost = mylar.CONFIG.SAB_HOST
if sabusername is None:
sabusername = mylar.CONFIG.SAB_USERNAME
if sabpassword is None:
sabpassword = mylar.CONFIG.SAB_PASSWORD
if sabapikey is None:
sabapikey = mylar.CONFIG.SAB_APIKEY
logger.fdebug('Now attempting to test SABnzbd connection')
#if user/pass given, we can auto-fill the API ;)
if sabusername is None or sabpassword is None:
logger.error('No Username / Password provided for SABnzbd credentials. Unable to test API key')
return "Invalid Username/Password provided"
logger.fdebug('testing connection to SABnzbd @ ' + sabhost)
if sabhost.endswith('/'):
sabhost = sabhost
else:
sabhost = sabhost + '/'
querysab = sabhost + 'api'
payload = {'mode': 'get_config',
'section': 'misc',
'output': 'json',
'keyword': 'api_key',
'apikey': sabapikey}
if sabhost.startswith('https'):
verify = True
else:
verify = False
version = 'Unknown'
try:
v = requests.get(querysab, params={'mode': 'version'}, verify=verify)
if str(v.status_code) == '200':
logger.fdebug('sabnzbd version: %s' % v.content)
version = v.text
r = requests.get(querysab, params=payload, verify=verify)
except Exception, e:
logger.warn('Error fetching data from %s: %s' % (querysab, e))
if requests.exceptions.SSLError:
logger.warn('Cannot verify ssl certificate. Attempting to authenticate with no ssl-certificate verification.')
try:
from requests.packages.urllib3 import disable_warnings
disable_warnings()
except:
logger.warn('Unable to disable https warnings. Expect some spam if using https nzb providers.')
verify = False
try:
v = requests.get(querysab, params={'mode': 'version'}, verify=verify)
if str(v.status_code) == '200':
logger.fdebug('sabnzbd version: %s' % v.text)
version = v.text
r = requests.get(querysab, params=payload, verify=verify)
except Exception, e:
logger.warn('Error fetching data from %s: %s' % (sabhost, e))
return 'Unable to retrieve data from SABnzbd'
else:
return 'Unable to retrieve data from SABnzbd'
logger.fdebug('status code: ' + str(r.status_code))
if str(r.status_code) != '200':
logger.warn('Unable to properly query SABnzbd @' + sabhost + ' [Status Code returned: ' + str(r.status_code) + ']')
data = False
else:
data = r.json()
try:
q_apikey = data['config']['misc']['api_key']
except:
logger.error('Error detected attempting to retrieve SAB data using FULL APIKey')
if all([sabusername is not None, sabpassword is not None]):
try:
sp = sabparse.sabnzbd(sabhost, sabusername, sabpassword)
q_apikey = sp.sab_get()
except Exception, e:
logger.warn('Error fetching data from %s: %s' % (sabhost, e))
if q_apikey is None:
return "Invalid APIKey provided"
mylar.CONFIG.SAB_APIKEY = q_apikey
logger.info('APIKey provided is the FULL APIKey which is the correct key. You still need to SAVE the config for the changes to be applied.')
logger.info('Connection to SABnzbd tested sucessfully')
mylar.CONFIG.SAB_VERSION = version
return json.dumps({"status": "Successfully verified APIkey.", "version": str(version)})
SABtest.exposed = True
def NZBGet_test(self, nzbhost=None, nzbport=None, nzbusername=None, nzbpassword=None):
if nzbhost is None:
nzbhost = mylar.CONFIG.NZBGET_HOST
if nzbport is None:
nzbport = mylar.CONFIG.NZBGET_PORT
if nzbusername is None:
nzbusername = mylar.CONFIG.NZBGET_USERNAME
if nzbpassword is None:
nzbpassword = mylar.CONFIG.NZBGET_PASSWORD
logger.fdebug('Now attempting to test NZBGet connection')
logger.info('Now testing connection to NZBGet @ %s:%s' % (nzbhost, nzbport))
if nzbhost[:5] == 'https':
protocol = 'https'
nzbgethost = nzbhost[8:]
elif nzbhost[:4] == 'http':
protocol = 'http'
nzbgethost = nzbhost[7:]
url = '%s://'
nzbparams = protocol,
if all([nzbusername is not None, nzbpassword is not None]):
url = url + '%s:%s@'
nzbparams = nzbparams + (nzbusername, nzbpassword)
elif nzbusername is not None:
url = url + '%s@'
nzbparams = nzbparams + (nzbusername,)
url = url + '%s:%s/xmlrpc'
nzbparams = nzbparams + (nzbgethost, nzbport,)
nzb_url = (url % nzbparams)
import xmlrpclib
nzbserver = xmlrpclib.ServerProxy(nzb_url)
try:
r = nzbserver.status()
except Exception as e:
logger.warn('Error fetching data: %s' % e)
return 'Unable to retrieve data from NZBGet'
logger.info('Successfully verified connection to NZBGet at %s:%s' % (nzbgethost, nzbport))
return "Successfully verified connection to NZBGet"
NZBGet_test.exposed = True
def shutdown(self):
mylar.SIGNAL = 'shutdown'
message = 'Shutting Down...'
return serve_template(templatename="shutdown.html", title="Shutting Down", message=message, timer=15)
return page
shutdown.exposed = True
def restart(self):
mylar.SIGNAL = 'restart'
message = 'Restarting...'
return serve_template(templatename="shutdown.html", title="Restarting", message=message, timer=30)
restart.exposed = True
def update(self):
mylar.SIGNAL = 'update'
message = 'Updating...<br/><small>Main screen will appear in 60s</small>'
return serve_template(templatename="shutdown.html", title="Updating", message=message, timer=30)
update.exposed = True
def getInfo(self, ComicID=None, IssueID=None):
from mylar import cache
info_dict = cache.getInfo(ComicID, IssueID)
return simplejson.dumps(info_dict)
getInfo.exposed = True
def getComicArtwork(self, ComicID=None, imageURL=None):
from mylar import cache
logger.info(u"Retrieving image for : " + comicID)
return cache.getArtwork(ComicID, imageURL)
getComicArtwork.exposed = True
def findsabAPI(self, sabhost=None, sabusername=None, sabpassword=None):
sp = sabparse.sabnzbd(sabhost, sabusername, sabpassword)
sabapi = sp.sab_get()
logger.info('SAB APIKey found as : ' + str(sabapi) + '. You still have to save the config to retain this setting.')
mylar.CONFIG.SAB_APIKEY = sabapi
return sabapi
findsabAPI.exposed = True
def generateAPI(self):
import hashlib, random
apikey = hashlib.sha224(str(random.getrandbits(256))).hexdigest()[0:32]
logger.info("New API generated")
mylar.CONFIG.API_KEY = apikey
return apikey
generateAPI.exposed = True
def api(self, *args, **kwargs):
from mylar.api import Api
a = Api()
a.checkParams(*args, **kwargs)
data = a.fetchData()
return data
api.exposed = True
def opds(self, *args, **kwargs):
from mylar.opds import OPDS
op = OPDS()
op.checkParams(*args, **kwargs)
data = op.fetchData()
return data
opds.exposed = True
def downloadthis(self, pathfile=None):
#pathfile should be escaped via the |u tag from within the html call already.
logger.fdebug('filepath to retrieve file from is : ' + pathfile)
from cherrypy.lib.static import serve_download
return serve_download(pathfile)
downloadthis.exposed = True
def IssueInfo(self, filelocation, comicname=None, issue=None, date=None, title=None):
filelocation = filelocation.encode('ASCII')
filelocation = urllib.unquote_plus(filelocation).decode('utf8')
issuedetails = helpers.IssueDetails(filelocation)
if issuedetails:
issueinfo = '<table width="500"><tr><td>'
issueinfo += '<img style="float: left; padding-right: 10px" src=' + issuedetails[0]['IssueImage'] + ' height="400" width="263">'
seriestitle = issuedetails[0]['series']
if any([seriestitle == 'None', seriestitle is None]):
seriestitle = comicname
issuenumber = issuedetails[0]['issue_number']
if any([issuenumber == 'None', issuenumber is None]):
issuenumber = issue
issuetitle = issuedetails[0]['title']
if any([issuetitle == 'None', issuetitle is None]):
issuetitle = title
issueinfo += '<h1><center><b>' + seriestitle + '</br>[#' + issuenumber + ']</b></center></h1>'
issueinfo += '<center>"' + issuetitle + '"</center></br>'
issueinfo += '</br><p class="alignleft">' + str(issuedetails[0]['pagecount']) + ' pages</p>'
if all([issuedetails[0]['day'] is None, issuedetails[0]['month'] is None, issuedetails[0]['year'] is None]):
issueinfo += '<p class="alignright">(' + str(date) + ')</p></br>'
else:
issueinfo += '<p class="alignright">(' + str(issuedetails[0]['year']) + '-' + str(issuedetails[0]['month']) + '-' + str(issuedetails[0]['day']) + ')</p></br>'
if not any([issuedetails[0]['writer'] == 'None', issuedetails[0]['writer'] is None]):
issueinfo += 'Writer: ' + issuedetails[0]['writer'] + '</br>'
if not any([issuedetails[0]['penciller'] == 'None', issuedetails[0]['penciller'] is None]):
issueinfo += 'Penciller: ' + issuedetails[0]['penciller'] + '</br>'
if not any([issuedetails[0]['inker'] == 'None', issuedetails[0]['inker'] is None]):
issueinfo += 'Inker: ' + issuedetails[0]['inker'] + '</br>'
if not any([issuedetails[0]['colorist'] == 'None', issuedetails[0]['colorist'] is None]):
issueinfo += 'Colorist: ' + issuedetails[0]['colorist'] + '</br>'
if not any([issuedetails[0]['letterer'] == 'None', issuedetails[0]['letterer'] is None]):
issueinfo += 'Letterer: ' + issuedetails[0]['letterer'] + '</br>'
if not any([issuedetails[0]['editor'] == 'None', issuedetails[0]['editor'] is None]):
issueinfo += 'Editor: ' + issuedetails[0]['editor'] + '</br>'
issueinfo += '</td></tr>'
#issueinfo += '<img src="interfaces/default/images/rename.png" height="25" width="25"></td></tr>'
issuesumm = None
if all([issuedetails[0]['summary'] == 'None', issuedetails[0]['summary'] is None]):
issuesumm = 'No summary available within metatagging.'
else:
if len(issuedetails[0]['summary']) > 1000:
issuesumm = issuedetails[0]['summary'][:1000] + '...'
else:
issuesumm = issuedetails[0]['summary']
issueinfo += '<tr><td>Summary: ' + issuesumm + '</br></td></tr>'
issueinfo += '<tr><td><center>' + os.path.split(filelocation)[1] + '</center>'
issueinfo += '</td></tr></table>'
else:
ErrorPNG = 'interfaces/default/images/symbol_exclamation.png'
issueinfo = '<table width="300"><tr><td>'
issueinfo += '<img style="float: left; padding-right: 10px" src=' + ErrorPNG + ' height="128" width="128">'
issueinfo += '<h1><center><b>ERROR</b></center></h1></br>'
issueinfo += '<center>Unable to retrieve metadata from within cbz file</center></br>'
issueinfo += '<center>Maybe you should try and tag the file again?</center></br>'
issueinfo += '<tr><td><center>' + os.path.split(filelocation)[1] + '</center>'
issueinfo += '</td></tr></table>'
return issueinfo
IssueInfo.exposed = True
def manual_metatag(self, dirName, issueid, filename, comicid, comversion, seriesyear=None, group=False):
module = '[MANUAL META-TAGGING]'
try:
import cmtagmylar
if mylar.CONFIG.CMTAG_START_YEAR_AS_VOLUME:
if all([seriesyear is not None, seriesyear != 'None']):
vol_label = seriesyear
else:
logger.warn('Cannot populate the year for the series for some reason. Dropping down to numeric volume label.')
vol_label = comversion
else:
vol_label = comversion
metaresponse = cmtagmylar.run(dirName, issueid=issueid, filename=filename, comversion=vol_label, manualmeta=True)
except ImportError:
logger.warn(module + ' comictaggerlib not found on system. Ensure the ENTIRE lib directory is located within mylar/lib/comictaggerlib/ directory.')
metaresponse = "fail"
if metaresponse == "fail":
logger.fdebug(module + ' Unable to write metadata successfully - check mylar.log file.')
return
elif metaresponse == "unrar error":
logger.error(module + ' This is a corrupt archive - whether CRC errors or it is incomplete. Marking as BAD, and retrying a different copy.')
return
#launch failed download handling here.
else:
dst = os.path.join(dirName, os.path.split(metaresponse)[1])
fail = False
try:
shutil.copy(metaresponse, dst)
logger.info('%s Sucessfully wrote metadata to .cbz (%s) - Continuing..' % (module, os.path.split(metaresponse)[1]))
except Exception as e:
if str(e.errno) == '2':
try:
if mylar.CONFIG.MULTIPLE_DEST_DIRS is not None and mylar.CONFIG.MULTIPLE_DEST_DIRS != 'None' and os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(dirName)) != dirName:
dst = os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(dirName))
shutil.copy(metaresponse, dst)
logger.info('%s Sucessfully wrote metadata to .cbz (%s) - Continuing..' % (module, os.path.split(metaresponse)[1]))
except Exception as e:
logger.warn('%s [%s] Unable to complete metatagging : %s [%s]' % (module, dst, e, e.errno))
fail = True
else:
logger.warn('%s [%s] Unable to complete metatagging : %s [%s]' % (module, dst, e, e.errno))
fail = True
cache_dir = os.path.split(metaresponse)[0]
if os.path.isfile(metaresponse):
try:
os.remove(metaresponse)
except OSError:
pass
if not os.listdir(cache_dir):
logger.fdebug('%s Tidying up. Deleting temporary cache directory: %s' % (module, cache_dir))
try:
shutil.rmtree(cache_dir)
except Exception as e:
logger.warn(module + ' Unable to remove temporary directory: %s' % cache_dir)
else:
logger.fdebug('Failed to remove temporary directory: %s' % cache_dir)
if filename is not None:
if os.path.isfile(filename) and os.path.split(filename)[1].lower() != os.path.split(metaresponse)[1].lower():
try:
logger.fdebug('%s Removing original filename: %s' % (module, filename))
os.remove(filename)
except OSError:
pass
if any([group is False, fail is False]):
updater.forceRescan(comicid)
manual_metatag.exposed = True
def group_metatag(self, ComicID, dirName=None):
myDB = db.DBConnection()
cinfo = myDB.selectone('SELECT ComicLocation, ComicVersion, ComicYear, ComicName FROM comics WHERE ComicID=?', [ComicID]).fetchone()
groupinfo = myDB.select('SELECT * FROM issues WHERE ComicID=? and Location is not NULL', [ComicID])
if groupinfo is None:
logger.warn('No issues physically exist within the series directory for me to (re)-tag.')
return
if dirName is None:
meta_dir = cinfo['ComicLocation']
else:
meta_dir = dirName
for ginfo in groupinfo:
#if multiple_dest_dirs is in effect, metadir will be pointing to the wrong location and cause a 'Unable to create temporary cache location' error message
self.manual_metatag(meta_dir, ginfo['IssueID'], os.path.join(meta_dir, ginfo['Location']), ComicID, comversion=cinfo['ComicVersion'], seriesyear=cinfo['ComicYear'], group=True)
updater.forceRescan(ComicID)
logger.info('[SERIES-METATAGGER][' + cinfo['ComicName'] + ' (' + cinfo['ComicYear'] + ')] Finished doing a complete series (re)tagging of metadata.')
group_metatag.exposed = True
def CreateFolders(self, createfolders=None):
if createfolders:
mylar.CONFIG.CREATE_FOLDERS = int(createfolders)
#mylar.config_write()
CreateFolders.exposed = True
def getPushbulletDevices(self, api=None):
notifythis = notifiers.pushbullet
result = notifythis.get_devices(api)
if result:
return result
else:
return 'Error sending Pushbullet notifications.'
getPushbulletDevices.exposed = True
def syncfiles(self):
#3 status' exist for the readlist.
# Added (Not Read) - Issue is added to the readlist and is awaiting to be 'sent' to your reading client.
# Read - Issue has been read
# Not Read - Issue has been downloaded to your reading client after the syncfiles has taken place.
read = readinglist.Readinglist()
threading.Thread(target=read.syncreading).start()
syncfiles.exposed = True
def search_32p(self, search=None):
return mylar.rsscheck.torrents(pickfeed='4', seriesname=search)
search_32p.exposed = True
def testprowl(self):
prowl = notifiers.prowl()
result = prowl.test_notify()
if result:
return "Successfully sent Prowl test - check to make sure it worked"
else:
return "Error sending test message to Prowl"
testprowl.exposed = True
def testboxcar(self):
boxcar = notifiers.boxcar()
result = boxcar.test_notify()
if result:
return "Successfully sent Boxcar test - check to make sure it worked"
else:
return "Error sending test message to Boxcar"
testboxcar.exposed = True
def testpushover(self, apikey, userkey, device):
pushover = notifiers.PUSHOVER(test_apikey=apikey, test_userkey=userkey, test_device=device)
result = pushover.test_notify()
if result == True:
return "Successfully sent PushOver test - check to make sure it worked"
else:
logger.warn('Last six characters of the test variables used [APIKEY: %s][USERKEY: %s]' % (apikey[-6:], userkey[-6:]))
return "Error sending test message to Pushover"
testpushover.exposed = True
def testpushbullet(self, apikey):
pushbullet = notifiers.PUSHBULLET(test_apikey=apikey)
result = pushbullet.test_notify()
if result['status'] == True:
return result['message']
else:
logger.warn('APIKEY used for test was : %s' % apikey)
return result['message']
testpushbullet.exposed = True
def testtelegram(self, userid, token):
telegram = notifiers.TELEGRAM(test_userid=userid, test_token=token)
result = telegram.test_notify()
if result == True:
return "Successfully sent Telegram test - check to make sure it worked"
else:
logger.warn('Test variables used [USERID: %s][TOKEN: %s]' % (userid, token))
return "Error sending test message to Telegram"
testtelegram.exposed = True
def testslack(self, webhook_url):
slack = notifiers.SLACK(test_webhook_url=webhook_url)
result = slack.test_notify()
if result == True:
return "Successfully sent Slack test - check to make sure it worked"
else:
logger.warn('Test variables used [WEBHOOK_URL: %s][USERNAME: %s]' % (webhook_url, username))
return "Error sending test message to Slack"
testslack.exposed = True
def testemail(self, emailfrom, emailto, emailsvr, emailport, emailuser, emailpass, emailenc):
email = notifiers.EMAIL(test_emailfrom=emailfrom, test_emailto=emailto, test_emailsvr=emailsvr, test_emailport=emailport, test_emailuser=emailuser, test_emailpass=emailpass, test_emailenc=emailenc)
result = email.test_notify()
if result == True:
return "Successfully sent email. Check your mailbox."
else:
logger.warn('Email test has gone horribly wrong. Variables used were [FROM: %s] [TO: %s] [SERVER: %s] [PORT: %s] [USER: %s] [PASSWORD: ********] [ENCRYPTION: %s]' % (emailfrom, emailto, emailsvr, emailport, emailuser, emailenc))
return "Error sending test message via email"
testemail.exposed = True
def testrtorrent(self, host, username, password, auth, verify, rpc_url):
import torrent.clients.rtorrent as TorClient
client = TorClient.TorrentClient()
ca_bundle = None
if mylar.CONFIG.RTORRENT_CA_BUNDLE is not None:
ca_bundle = mylar.CONFIG.RTORRENT_CA_BUNDLE
rclient = client.connect(host, username, password, auth, verify, rpc_url, ca_bundle, test=True)
if not rclient:
logger.warn('Could not establish connection to %s' % host)
return '[rTorrent] Error establishing connection to Rtorrent'
else:
if rclient['status'] is False:
logger.warn('[rTorrent] Could not establish connection to %s. Error returned: %s' % (host, rclient['error']))
return 'Error establishing connection to rTorrent'
else:
logger.info('[rTorrent] Successfully validated connection to %s [v%s]' % (host, rclient['version']))
return 'Successfully validated rTorrent connection'
testrtorrent.exposed = True
def testqbit(self, host, username, password):
import torrent.clients.qbittorrent as QbitClient
qc = QbitClient.TorrentClient()
qclient = qc.connect(host, username, password, True)
if not qclient:
logger.warn('[qBittorrent] Could not establish connection to %s' % host)
return 'Error establishing connection to Qbittorrent'
else:
if qclient['status'] is False:
logger.warn('[qBittorrent] Could not establish connection to %s. Error returned: %s' % (host, qclient['error']))
return 'Error establishing connection to Qbittorrent'
else:
logger.info('[qBittorrent] Successfully validated connection to %s [v%s]' % (host, qclient['version']))
return 'Successfully validated qBittorrent connection'
testqbit.exposed = True
def testdeluge(self, host, username, password):
import torrent.clients.deluge as DelugeClient
client = DelugeClient.TorrentClient()
dclient = client.connect(host, username, password, True)
if not dclient:
logger.warn('[Deluge] Could not establish connection to %s' % host)
return 'Error establishing connection to Deluge'
else:
if dclient['status'] is False:
logger.warn('[Deluge] Could not establish connection to %s. Error returned: %s' % (host, dclient['error']))
return 'Error establishing connection to Deluge'
else:
logger.info('[Deluge] Successfully validated connection to %s [daemon v%s; libtorrent v%s]' % (host, dclient['daemon_version'], dclient['libtorrent_version']))
return 'Successfully validated Deluge connection'
testdeluge.exposed = True
def testnewznab(self, name, host, ssl, apikey):
logger.fdebug('ssl/verify: %s' % ssl)
if 'ssl' == '0' or ssl == '1':
ssl = bool(int(ssl))
else:
if ssl == 'false':
ssl = False
else:
ssl = True
result = helpers.newznab_test(name, host, ssl, apikey)
if result is True:
logger.info('Successfully tested %s [%s] - valid api response received' % (name, host))
return 'Successfully tested %s!' % name
else:
logger.warn('Testing failed to %s [HOST:%s][SSL:%s]' % (name, host, bool(ssl)))
return 'Error - failed running test for %s' % name
testnewznab.exposed = True
def testtorznab(self, name, host, ssl, apikey):
logger.fdebug('ssl/verify: %s' % ssl)
if 'ssl' == '0' or ssl == '1':
ssl = bool(int(ssl))
else:
if ssl == 'false':
ssl = False
else:
ssl = True
result = helpers.torznab_test(name, host, ssl, apikey)
if result is True:
logger.info('Successfully tested %s [%s] - valid api response received' % (name, host))
return 'Successfully tested %s!' % name
else:
print result
logger.warn('Testing failed to %s [HOST:%s][SSL:%s]' % (name, host, bool(ssl)))
return 'Error - failed running test for %s' % name
testtorznab.exposed = True
def orderThis(self, **kwargs):
return
orderThis.exposed = True
def torrentit(self, issueid=None, torrent_hash=None, download=False):
#make sure it's bool'd here.
if download == 'True':
download = True
else:
download = False
if mylar.CONFIG.AUTO_SNATCH is False:
logger.warn('Auto-Snatch is not enabled - this will ONLY work with auto-snatch enabled and configured. Aborting request.')
return 'Unable to complete request - please enable auto-snatch if required'
torrent_info = helpers.torrentinfo(issueid, torrent_hash, download)
if torrent_info:
torrent_name = torrent_info['name']
torrent_info['filesize'] = helpers.human_size(torrent_info['total_filesize'])
torrent_info['download'] = helpers.human_size(torrent_info['download_total'])
torrent_info['upload'] = helpers.human_size(torrent_info['upload_total'])
torrent_info['seedtime'] = helpers.humanize_time(amount=int(time.time()) - torrent_info['time_started'])
logger.info("Client: %s", mylar.CONFIG.RTORRENT_HOST)
logger.info("Directory: %s", torrent_info['folder'])
logger.info("Name: %s", torrent_info['name'])
logger.info("Hash: %s", torrent_info['hash'])
logger.info("FileSize: %s", torrent_info['filesize'])
logger.info("Completed: %s", torrent_info['completed'])
logger.info("Downloaded: %s", torrent_info['download'])
logger.info("Uploaded: %s", torrent_info['upload'])
logger.info("Ratio: %s", torrent_info['ratio'])
logger.info("Seeding Time: %s", torrent_info['seedtime'])
if torrent_info['label']:
logger.info("Torrent Label: %s", torrent_info['label'])
ti = '<table><tr><td>'
ti += '<center><b>' + torrent_name + '</b></center></br>'
if torrent_info['completed'] and download is True:
ti += '<br><center><tr><td>AUTO-SNATCH ENABLED: ' + torrent_info['snatch_status'] + '</center></td></tr>'
ti += '<tr><td><center>Hash: ' + torrent_info['hash'] + '</center></td></tr>'
ti += '<tr><td><center>Location: ' + os.path.join(torrent_info['folder'], torrent_name) + '</center></td></tr></br>'
ti += '<tr><td><center>Filesize: ' + torrent_info['filesize'] + '</center></td></tr>'
ti += '<tr><td><center>' + torrent_info['download'] + ' DOWN / ' + torrent_info['upload'] + ' UP</center></td></tr>'
ti += '<tr><td><center>Ratio: ' + str(torrent_info['ratio']) + '</center></td></tr>'
ti += '<tr><td><center>Seedtime: ' + torrent_info['seedtime'] + '</center></td</tr>'
ti += '</table>'
logger.info('torrent_info:%s' % torrent_info)
#commenting out the next 2 lines will return the torrent information to the screen
#fp = mylar.process.Process(torrent_info['filepath'], torrent_info['dst_folder'], issueid=torrent_info['issueid'], failed=failed)
#fp.post_process()
else:
torrent_name = 'Not Found'
ti = 'Torrent not found (' + str(torrent_hash)
return ti
torrentit.exposed = True
def get_the_hash(self, filepath):
import hashlib, StringIO
import rtorrent.lib.bencode as bencode
# Open torrent file
torrent_file = open(os.path.join('/home/hero/mylar/cache', filepath), "rb")
metainfo = bencode.decode(torrent_file.read())
info = metainfo['info']
thehash = hashlib.sha1(bencode.encode(info)).hexdigest().upper()
logger.info('Hash: ' + thehash)
get_the_hash.exposed = True
def download_0day(self, week):
logger.info('Now attempting to search for 0-day pack for week: %s' % week)
#week contains weekinfo['midweek'] = YYYY-mm-dd of Wednesday of the given week's pull
foundcom, prov = search.search_init('0-Day Comics Pack - %s.%s' % (week[:4],week[5:]), None, week[:4], None, None, week, week, None, allow_packs=True, oneoff=True)
download_0day.exposed = True
def test_32p(self, username, password):
import auth32p
tmp = auth32p.info32p(test={'username': username, 'password': password})
rtnvalues = tmp.authenticate()
if rtnvalues['status'] is True:
return json.dumps({"status": "Successfully Authenticated.", "inkdrops": mylar.INKDROPS_32P})
else:
return json.dumps({"status": "Could not Authenticate.", "inkdrops": mylar.INKDROPS_32P})
test_32p.exposed = True
def check_ActiveDDL(self):
myDB = db.DBConnection()
active = myDB.selectone("SELECT * FROM DDL_INFO WHERE STATUS = 'Downloading'").fetchone()
if active is None:
return json.dumps({'status': 'There are no active downloads currently being attended to',
'percent': 0,
'a_series': None,
'a_year': None,
'a_filename': None,
'a_size': None,
'a_id': None})
else:
filelocation = os.path.join(mylar.CONFIG.DDL_LOCATION, active['filename'])
#logger.fdebug('checking file existance: %s' % filelocation)
if os.path.exists(filelocation) is True:
filesize = os.stat(filelocation).st_size
cmath = int(float(filesize*100)/int(int(active['remote_filesize'])*100) * 100)
#logger.fdebug('ACTIVE DDL: %s %s [%s]' % (active['filename'], cmath, 'Downloading'))
return json.dumps({'status': 'Downloading',
'percent': "%s%s" % (cmath, '%'),
'a_series': active['series'],
'a_year': active['year'],
'a_filename': active['filename'],
'a_size': active['size'],
'a_id': active['id']})
else:
# myDB.upsert('ddl_info', {'status': 'Incomplete'}, {'id': active['id']})
return json.dumps({'a_id': active['id'], 'status': 'File does not exist in %s.</br> This probably needs to be restarted (use the option in the GUI)' % filelocation, 'percent': 0})
check_ActiveDDL.exposed = True
def create_readlist(self, list=None, weeknumber=None, year=None):
# ({
# "PUBLISHER": weekly['PUBLISHER'],
# "ISSUE": weekly['ISSUE'],
# "COMIC": weekly['COMIC'],
# "STATUS": tmp_status,
# "COMICID": weekly['ComicID'],
# "ISSUEID": weekly['IssueID'],
# "HAVEIT": haveit,
# "LINK": linkit,
# "AUTOWANT": False
# })
issuelist = []
logger.info('weeknumber: %s' % weeknumber)
logger.info('year: %s' % year)
weeklyresults = []
if weeknumber is not None:
myDB = db.DBConnection()
w_results = myDB.select("SELECT * from weekly WHERE weeknumber=? AND year=?", [int(weeknumber),int(year)])
watchlibrary = helpers.listLibrary()
issueLibrary = helpers.listIssues(weeknumber, year)
oneofflist = helpers.listoneoffs(weeknumber, year)
for weekly in w_results:
xfound = False
tmp_status = weekly['Status']
issdate = None
if weekly['ComicID'] in watchlibrary:
haveit = watchlibrary[weekly['ComicID']]
if all([mylar.CONFIG.AUTOWANT_UPCOMING, tmp_status == 'Skipped']):
tmp_status = 'Wanted'
for x in issueLibrary:
if weekly['IssueID'] == x['IssueID']:
xfound = True
tmp_status = x['Status']
issdate = x['IssueYear']
break
else:
xlist = [x['Status'] for x in oneofflist if x['IssueID'] == weekly['IssueID']]
if xlist:
haveit = 'OneOff'
tmp_status = xlist[0]
issdate = None
else:
haveit = "No"
x = None
try:
x = float(weekly['ISSUE'])
except ValueError, e:
if 'au' in weekly['ISSUE'].lower() or 'ai' in weekly['ISSUE'].lower() or '.inh' in weekly['ISSUE'].lower() or '.now' in weekly['ISSUE'].lower() or '.mu' in weekly['ISSUE'].lower() or '.hu' in weekly['ISSUE'].lower():
x = weekly['ISSUE']
if x is not None:
weeklyresults.append({
"PUBLISHER": weekly['PUBLISHER'],
"ISSUE": weekly['ISSUE'],
"COMIC": weekly['COMIC'],
"STATUS": tmp_status,
"COMICID": weekly['ComicID'],
"ISSUEID": weekly['IssueID'],
"HAVEIT": haveit,
"ISSUEDATE": issdate
})
weeklylist = sorted(weeklyresults, key=itemgetter('PUBLISHER', 'COMIC'), reverse=False)
for ab in weeklylist:
if ab['HAVEIT'] == ab['COMICID']:
lb = myDB.selectone('SELECT ComicVersion, Type, ComicYear from comics WHERE ComicID=?', [ab['COMICID']]).fetchone()
issuelist.append({'IssueNumber': ab['ISSUE'],
'ComicName': ab['COMIC'],
'ComicID': ab['COMICID'],
'IssueID': ab['ISSUEID'],
'Status': ab['STATUS'],
'Publisher': ab['PUBLISHER'],
'ComicVolume': lb['ComicVersion'],
'ComicYear': lb['ComicYear'],
'ComicType': lb['Type'],
'IssueYear': ab['ISSUEDATE']})
from mylar import cbl
ab = cbl.dict2xml(issuelist)
#a = cbl.CreateList(issuelist)
#ab = a.createComicRackReadlist()
logger.info('returned.')
logger.info(ab)
create_readlist.exposed = True
def downloadBanner(self, **kwargs):
storyarcid = kwargs['storyarcid']
url = kwargs['url']
storyarcname = kwargs['storyarcname']
logger.info('storyarcid: %s' % storyarcid)
logger.info('url: %s' % url)
ext = url[-4:]
for i in ['.jpg', '.png', '.jpeg']:
if i in url:
ext = i
break
banner = os.path.join(mylar.CONFIG.CACHE_DIR, 'storyarcs', (str(storyarcid) + '-banner' + ext))
r = requests.get(url, stream=True)
if str(r.status_code) != '200':
logger.warn('Unable to download image from URL: %s [Status Code returned:%s]' % (url, r.status_code))
else:
if r.headers.get('Content-Encoding') == 'gzip':
import gzip
from StringIO import StringIO
buf = StringIO(r.content)
f = gzip.GzipFile(fileobj=buf)
with open(banner, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
logger.info('Successfully wrote image to cache directory: %s' % banner)
import get_image_size
image = get_image_size.get_image_metadata(banner)
imageinfo = json.loads(get_image_size.Image.to_str_json(image))
logger.info('imageinfo: %s' % imageinfo)
raise cherrypy.HTTPRedirect("detailStoryArc?StoryArcID=%s&StoryArcName=%s" % (storyarcid, storyarcname))
downloadBanner.exposed = True
def manageBanner(self, comicid, action, height=None, width=None):
rootpath = os.path.join(mylar.CONFIG.CACHE_DIR, 'storyarcs')
if action == 'delete':
delete = False
ext = ['.jpg', '.png', '.jpeg']
loc = os.path.join(rootpath, str(comicid) + '-banner')
for x in ['.jpg', '.png', '.jpeg']:
if os.path.isfile(loc +x):
os.remove(loc+x)
deleted = True
break
if deleted is True:
logger.info('Successfully deleted banner image for the given storyarc.')
else:
logger.warn('Unable to located banner image in cache folder...')
elif action == 'save':
filename = None
dir = os.listdir(rootpath)
for fname in dir:
if str(comicid) in fname:
ext = os.path.splitext(fname)[1]
filepath = os.path.join(rootpath, fname)
break
#if 'H' in fname:
# bannerheight = fname[fname.find('H')+1:fname.find('.')]
# logger.info('bannerheight found at : %s' % bannerheight)
#ext = ['.jpg', '.png', '.jpeg']
#ext = None
#loc = os.path.join(mylar.CONFIG.CACHE_DIR, 'storyarcs', str(comicid) + '-banner')
#for x in ['.jpg', '.png', '.jpeg']:
# if os.path.isfile(loc +x):
# ext = x
# break
if filepath is not None:
os.rename(filepath, os.path.join(rootpath, (str(comicid) + '-bannerH' + str(height) + ext)))
logger.info('successfully saved %s to new dimensions of banner : 960 x %s' % (str(comicid) + '-bannerH' + str(height) + ext, height))
else:
logger.warn('unable to locate %s in cache directory in order to save' % filepath)
manageBanner.exposed = True
def choose_specific_download(self, **kwargs): #manual=True):
try:
action = kwargs['action']
except:
action = False
try:
comicvolume = kwargs['comicvolume']
except:
comicvolume = None
if all([kwargs['issueid'] != 'None', kwargs['issueid'] is not None]) and action is False:
issueid = kwargs['issueid']
logger.info('checking for: %s' % issueid)
results = search.searchforissue(issueid, manual=True)
else:
results = self.queueissue(kwargs['mode'], ComicName=kwargs['comicname'], ComicID=kwargs['comicid'], IssueID=kwargs['issueid'], ComicIssue=kwargs['issue'], ComicVersion=comicvolume, Publisher=kwargs['publisher'], pullinfo=kwargs['pullinfo'], pullweek=kwargs['pullweek'], pullyear=kwargs['pullyear'], manual=True)
myDB = db.DBConnection()
r = []
for x in mylar.COMICINFO: #results:
ctrlval = {'provider': x['provider'],
'id': x['nzbid']}
newval = {'kind': x['kind'],
'sarc': x['SARC'],
'issuearcid': x['IssueArcID'],
'comicname': x['ComicName'],
'comicid': x['ComicID'],
'issueid': x['IssueID'],
'issuenumber': x['IssueNumber'],
'volume': x['ComicVolume'],
'oneoff': x['oneoff'],
'fullprov': x['nzbprov'],
'modcomicname': x['modcomicname'],
'name': x['nzbtitle'],
'link': x['link'],
'size': x['size'],
'pack_numbers': x['pack_numbers'],
'pack_issuelist': x['pack_issuelist'],
'comicyear': x['comyear'],
'issuedate': x['IssueDate'],
'tmpprov': x['tmpprov'],
'pack': x['pack']}
myDB.upsert('manualresults', newval, ctrlval)
r.append({'kind': x['kind'],
'provider': x['provider'],
'nzbtitle': x['nzbtitle'],
'nzbid': x['nzbid'],
'size': x['size'][:-1],
'tmpprov': x['tmpprov']})
#logger.fdebug('results returned: %s' % r)
cherrypy.response.headers['Content-type'] = 'application/json'
return json.dumps(r)
choose_specific_download.exposed = True
def download_specific_release(self, nzbid, provider, name):
myDB = db.DBConnection()
dsr = myDB.selectone('SELECT * FROM manualresults WHERE id=? AND tmpprov=? AND name=?', [nzbid, provider, name]).fetchone()
if dsr is None:
logger.warn('Unable to locate result - something is wrong. Try and manually search again?')
return
else:
oneoff = bool(int(dsr['oneoff']))
try:
pack = bool(int(dsr['pack']))
except:
pack = False
comicinfo = [{'ComicName': dsr['comicname'],
'ComicVolume': dsr['volume'],
'IssueNumber': dsr['issuenumber'],
'comyear': dsr['comicyear'],
'IssueDate': dsr['issuedate'],
'pack': pack,
'modcomicname': dsr['modcomicname'],
'oneoff': oneoff,
'SARC': dsr['sarc'],
'IssueArcID': dsr['issuearcid']}]
#logger.info('comicinfo: %s' % comicinfo)
newznabinfo = None
if dsr['kind'] == 'usenet':
link = dsr['link']
for newznab_info in mylar.CONFIG.EXTRA_NEWZNABS:
if dsr['provider'].lower() in newznab_info[0].lower():
if (newznab_info[5] == '1' or newznab_info[5] == 1):
if newznab_info[1].endswith('/'):
newznab_host = newznab_info[1]
else:
newznab_host = newznab_info[1] + '/'
newznab_api = newznab_info[3]
newznab_uid = newznab_info[4]
link = str(newznab_host) + 'api?apikey=' + str(newznab_api) + '&t=get&id=' + str(dsr['id'])
logger.info('newznab detected as : ' + str(newznab_info[0]) + ' @ ' + str(newznab_host))
logger.info('link : ' + str(link))
newznabinfo = (newznab_info[0], newznab_info[1], newznab_info[2], newznab_info[3], newznab_info[4])
else:
logger.error(str(newznab_info[0]) + ' is not enabled - unable to process retry request until provider is re-enabled.')
break
else:
link = nzbid
if oneoff is True:
mode = 'pullwant'
else:
mode = 'series'
try:
nzbname = search.nzbname_create(dsr['fullprov'], info=comicinfo, title=dsr['name'])
sresults = search.searcher(dsr['fullprov'], nzbname, comicinfo, link=link, IssueID=dsr['issueid'], ComicID=dsr['comicid'], tmpprov=dsr['tmpprov'], directsend=True, newznab=newznabinfo)
if sresults is not None:
updater.foundsearch(dsr['ComicID'], dsr['IssueID'], mode='series', provider=dsr['tmpprov'], hash=sresults['t_hash'])
except:
return False #json.dumps({'result': 'failure'})
else:
return True #json.dumps({'result': 'success'})
download_specific_release.exposed = True
def read_comic(self, ish_id, page_num, size):
from mylar.webviewer import WebViewer
wv = WebViewer()
page_num = int(page_num)
#cherrypy.session['ishid'] = ish_id
data = wv.read_comic(ish_id, page_num, size)
#data = wv.read_comic(ish_id)
return data
read_comic.exposed = True
| 350,353 | Python | .py | 5,819 | 42.691012 | 421 | 0.527228 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,262 | webstart.py | evilhero_mylar/mylar/webstart.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import cherrypy
import mylar
from mylar import logger
from mylar.webserve import WebInterface
from mylar.helpers import create_https_certificates
from mylar.api import REST
def initialize(options):
# HTTPS stuff stolen from sickbeard
enable_https = options['enable_https']
https_cert = options['https_cert']
https_key = options['https_key']
https_chain = options['https_chain']
if enable_https:
# If either the HTTPS certificate or key do not exist, try to make
# self-signed ones.
if not (https_cert and os.path.exists(https_cert)) or not (https_key and os.path.exists(https_key)):
if not create_https_certificates(https_cert, https_key):
logger.warn("Unable to create certificate and key. Disabling " \
"HTTPS")
enable_https = False
if not (os.path.exists(https_cert) and os.path.exists(https_key)):
logger.warn("Disabled HTTPS because of missing certificate and " \
"key.")
enable_https = False
options_dict = {
'server.socket_port': options['http_port'],
'server.socket_host': options['http_host'],
'server.thread_pool': 10,
'tools.encode.on': True,
'tools.encode.encoding': 'utf-8',
'tools.decode.on': True,
'log.screen': False,
'engine.autoreload.on': False,
}
if enable_https:
options_dict['server.ssl_certificate'] = https_cert
options_dict['server.ssl_private_key'] = https_key
if https_chain:
options_dict['server.ssl_certificate_chain'] = https_chain
protocol = "https"
else:
protocol = "http"
logger.info("Starting Mylar on %s://%s:%d%s" % (protocol,options['http_host'], options['http_port'], options['http_root']))
cherrypy.config.update(options_dict)
conf = {
'/': {
'tools.staticdir.root': os.path.join(mylar.PROG_DIR, 'data')
#'tools.proxy.on': True # pay attention to X-Forwarded-Proto header
},
'/interfaces': {
'tools.staticdir.on': True,
'tools.staticdir.dir': "interfaces"
},
'/images': {
'tools.staticdir.on': True,
'tools.staticdir.dir': "images"
},
'/css': {
'tools.staticdir.on': True,
'tools.staticdir.dir': "css"
},
'/js': {
'tools.staticdir.on': True,
'tools.staticdir.dir': "js"
},
'/favicon.ico': {
'tools.staticfile.on': True,
'tools.staticfile.filename': os.path.join(os.path.abspath(os.curdir), 'images' + os.sep + 'favicon.ico')
},
'/cache': {
'tools.staticdir.on': True,
'tools.staticdir.dir': mylar.CONFIG.CACHE_DIR
}
}
if options['http_password'] is not None:
#userpassdict = dict(zip((options['http_username'].encode('utf-8'),), (options['http_password'].encode('utf-8'),)))
#get_ha1= cherrypy.lib.auth_digest.get_ha1_dict_plain(userpassdict)
if options['authentication'] == 2:
# Set up a sessions based login page instead of using basic auth,
# using the credentials set for basic auth. Attempting to browse to
# a restricted page without a session token will result in a
# redirect to the login page. A sucessful login should then redirect
# to the originally requested page.
#
# Login sessions timeout after 43800 minutes (1 month) unless
# changed in the config.
cherrypy.tools.sessions.timeout = options['login_timeout']
conf['/'].update({
'tools.sessions.on': True,
'tools.auth.on': True,
'auth.forms_username': options['http_username'],
'auth.forms_password': options['http_password'],
# Set all pages to require authentication.
# You can also set auth requirements on a per-method basis by
# using the @require() decorator on the methods in webserve.py
'auth.require': []
})
# exempt api, login page and static elements from authentication requirements
for i in ('/api', '/auth/login', '/css', '/images', '/js', 'favicon.ico'):
if i in conf:
conf[i].update({'tools.auth.on': False})
else:
conf[i] = {'tools.auth.on': False}
elif options['authentication'] == 1:
conf['/'].update({
'tools.auth_basic.on': True,
'tools.auth_basic.realm': 'Mylar',
'tools.auth_basic.checkpassword': cherrypy.lib.auth_basic.checkpassword_dict(
{options['http_username']: options['http_password']})
})
conf['/api'] = {'tools.auth_basic.on': False}
rest_api = {
'/': {
# the api uses restful method dispatching
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
# all api calls require that the client passes HTTP basic authentication
'tools.auth_basic.on' : False,
}
}
if options['opds_authentication']:
user_list = {}
if len(options['opds_username']) > 0:
user_list[options['opds_username']] = options['opds_password']
if options['http_password'] is not None and options['http_username'] != options['opds_username']:
user_list[options['http_username']] = options['http_password']
conf['/opds'] = {'tools.auth.on': False,
'tools.auth_basic.on': True,
'tools.auth_basic.realm': 'Mylar OPDS',
'tools.auth_basic.checkpassword': cherrypy.lib.auth_basic.checkpassword_dict(user_list)}
else:
conf['/opds'] = {'tools.auth_basic.on': False, 'tools.auth.on': False}
# Prevent time-outs
cherrypy.engine.timeout_monitor.unsubscribe()
cherrypy.tree.mount(WebInterface(), str(options['http_root']), config = conf)
restroot = REST()
restroot.comics = restroot.Comics()
restroot.comic = restroot.Comic()
restroot.watchlist = restroot.Watchlist()
#restroot.issues = restroot.comic.Issues()
#restroot.issue = restroot.comic.Issue()
cherrypy.tree.mount(restroot, '/rest', config = rest_api)
try:
cherrypy.process.servers.check_port(options['http_host'], options['http_port'])
cherrypy.server.start()
except IOError:
print 'Failed to start on port: %i. Is something else running?' % (options['http_port'])
sys.exit(0)
cherrypy.server.wait()
| 7,551 | Python | .py | 166 | 35.614458 | 127 | 0.598316 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,263 | filechecker.py | evilhero_mylar/mylar/filechecker.py | #/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import sys
import glob
import shutil
import operator
import urllib
import logging
import unicodedata
import optparse
from fnmatch import fnmatch
import datetime as dt
import subprocess
from subprocess import CalledProcessError, check_output
import mylar
from mylar import logger, helpers
class FileChecker(object):
def __init__(self, dir=None, watchcomic=None, Publisher=None, AlternateSearch=None, manual=None, sarc=None, justparse=None, file=None, pp_mode=False):
#dir = full path to the series Comic Location (manual pp will just be psssing the already parsed filename)
if dir:
self.dir = dir
else:
self.dir = None
if watchcomic:
#watchcomic = unicode name of series that is being searched against
self.og_watchcomic = watchcomic
self.watchcomic = re.sub('\?', '', watchcomic).strip() #strip the ? sepearte since it affects the regex.
self.watchcomic = re.sub(u'\u2014', ' - ', watchcomic).strip() #replace the \u2014 with a normal - because this world is f'd up enough to have something like that.
self.watchcomic = re.sub(u'\u2013', ' - ', watchcomic).strip() #replace the \u2013 with a normal - because again, people are dumb.
if type(self.watchcomic) != str:
self.watchcomic = unicodedata.normalize('NFKD', self.watchcomic).encode('ASCII', 'ignore')
else:
self.watchcomic = None
if Publisher:
#publisher = publisher of watchcomic
self.publisher = Publisher
else:
self.publisher = None
#alternatesearch = list of alternate search names
if AlternateSearch:
self.AlternateSearch = AlternateSearch
else:
self.AlternateSearch = None
#manual = true / false if it's a manual post-processing run
if manual:
self.manual = manual
else:
self.manual = None
#sarc = true / false if it's being run against an existing story-arc
if sarc:
self.sarc = sarc
else:
self.sarc = None
#justparse = true/false when manually post-processing, will quickly parse the filename to find
#the series name in order to query the sql instead of cycling through each series in the watchlist.
if justparse:
self.justparse = True
else:
self.justparse = False
#file = parse just one filename (used primarily during import/scan)
if file:
self.file = file
self.justparse = True
else:
self.file = None
if pp_mode:
self.pp_mode = True
else:
self.pp_mode = False
self.failed_files = []
self.dynamic_handlers = ['/','-',':',';','\'',',','&','?','!','+','(',')','\u2014','\u2013']
self.dynamic_replacements = ['and','the']
self.rippers = ['-empire','-empire-hd','minutemen-','-dcp','Glorith-HD']
#pre-generate the AS_Alternates now
AS_Alternates = self.altcheck()
self.AS_Alt = AS_Alternates['AS_Alt']
self.AS_Tuple = AS_Alternates['AS_Tuple']
def listFiles(self):
comiclist = []
watchmatch = {}
dirlist = []
comiccnt = 0
if self.file:
runresults = self.parseit(self.dir, self.file)
return {'parse_status': runresults['parse_status'],
'sub': runresults['sub'],
'comicfilename': runresults['comicfilename'],
'comiclocation': runresults['comiclocation'],
'series_name': runresults['series_name'],
'series_name_decoded': runresults['series_name_decoded'],
'issueid': runresults['issueid'],
'dynamic_name': runresults['dynamic_name'],
'series_volume': runresults['series_volume'],
'alt_series': runresults['alt_series'],
'alt_issue': runresults['alt_issue'],
'issue_year': runresults['issue_year'],
'issue_number': runresults['issue_number'],
'scangroup': runresults['scangroup'],
'reading_order': runresults['reading_order'],
'booktype': runresults['booktype']
}
else:
filelist = self.traverse_directories(self.dir)
for files in filelist:
filedir = files['directory']
filename = files['filename']
filesize = files['comicsize']
if filename.startswith('.'):
continue
logger.debug('[FILENAME]: %s' % filename)
runresults = self.parseit(self.dir, filename, filedir)
if runresults:
try:
if runresults['parse_status']:
run_status = runresults['parse_status']
except:
if runresults['process_status']:
run_status = runresults['process_status']
if any([run_status == 'success', run_status == 'match']):
if self.justparse:
comiclist.append({
'sub': runresults['sub'],
'comicfilename': runresults['comicfilename'],
'comiclocation': runresults['comiclocation'],
'series_name': helpers.conversion(runresults['series_name']),
'series_name_decoded': runresults['series_name_decoded'],
'issueid': runresults['issueid'],
'alt_series': helpers.conversion(runresults['alt_series']),
'alt_issue': runresults['alt_issue'],
'dynamic_name': runresults['dynamic_name'],
'series_volume': runresults['series_volume'],
'issue_year': runresults['issue_year'],
'issue_number': runresults['issue_number'],
'scangroup': runresults['scangroup'],
'reading_order': runresults['reading_order'],
'booktype': runresults['booktype']
})
else:
comiclist.append({
'sub': runresults['sub'],
'ComicFilename': runresults['comicfilename'],
'ComicLocation': runresults['comiclocation'],
'ComicSize': files['comicsize'],
'ComicName': helpers.conversion(runresults['series_name']),
'SeriesVolume': runresults['series_volume'],
'IssueYear': runresults['issue_year'],
'JusttheDigits': runresults['justthedigits'],
'AnnualComicID': runresults['annual_comicid'],
'issueid': runresults['issueid'],
'scangroup': runresults['scangroup'],
'booktype': runresults['booktype']
})
comiccnt +=1
else:
#failure
self.failed_files.append({'parse_status': 'failure',
'sub': runresults['sub'],
'comicfilename': runresults['comicfilename'],
'comiclocation': runresults['comiclocation'],
'series_name': helpers.conversion(runresults['series_name']),
'series_volume': runresults['series_volume'],
'alt_series': helpers.conversion(runresults['alt_series']),
'alt_issue': runresults['alt_issue'],
'issue_year': runresults['issue_year'],
'issue_number': runresults['issue_number'],
'issueid': runresults['issueid'],
'scangroup': runresults['scangroup'],
'booktype': runresults['booktype']
})
watchmatch['comiccount'] = comiccnt
if len(comiclist) > 0:
watchmatch['comiclist'] = comiclist
else:
watchmatch['comiclist'] = []
if len(self.failed_files) > 0:
logger.info('FAILED FILES: %s' % self.failed_files)
return watchmatch
def parseit(self, path, filename, subpath=None):
#filename = filename.encode('ASCII').decode('utf8')
path_list = None
if subpath is None:
subpath = path
tmppath = None
path_list = None
else:
logger.fdebug('[CORRECTION] Sub-directory found. Altering path configuration.')
#basepath the sub if it exists to get the parent folder.
logger.fdebug('[SUB-PATH] Checking Folder Name for more information.')
#sub = re.sub(origpath, '', path).strip()})
logger.fdebug('[SUB-PATH] Original Path : %s' % path)
logger.fdebug('[SUB-PATH] Sub-directory : %s' % subpath)
subpath = helpers.conversion(subpath)
if 'windows' in mylar.OS_DETECT.lower():
if path in subpath:
ab = len(path)
tmppath = subpath[ab:]
else:
tmppath = subpath.replace(path, '').strip()
path_list = os.path.normpath(tmppath)
if '/' == path_list[0] or '\\' == path_list[0]:
#need to remove any leading slashes so the os join can properly join the components
path_list = path_list[1:]
logger.fdebug('[SUB-PATH] subpath set to : %s' % path_list)
#parse out the extension for type
comic_ext = ('.cbr','.cbz','.cb7','.pdf')
if os.path.splitext(filename)[1].endswith(comic_ext):
filetype = os.path.splitext(filename)[1]
else:
filetype = 'unknown'
#find the issue number first.
#split the file and then get all the relevant numbers that could possibly be an issue number.
#remove the extension.
modfilename = re.sub(filetype, '', filename).strip()
reading_order = None
#if it's a story-arc, make sure to remove any leading reading order #'s
if self.sarc and mylar.CONFIG.READ2FILENAME:
removest = modfilename.find('-') # the - gets removed above so we test for the first blank space...
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[SARC] Checking filename for Reading Order sequence - Reading Sequence Order found #: %s' % modfilename[:removest])
if modfilename[:removest].isdigit() and removest <= 3:
reading_order = {'reading_sequence': str(modfilename[:removest]),
'filename': filename[removest+1:]}
modfilename = modfilename[removest+1:]
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[SARC] Removed Reading Order sequence from subname. Now set to : %s' % modfilename)
#make sure all the brackets are properly spaced apart
if modfilename.find('\s') == -1:
#if no spaces exist, assume decimals being used as spacers (ie. nzb name)
modspacer = '.'
else:
modspacer = ' '
m = re.findall('[^()]+', modfilename)
cnt = 1
#2019-12-24----fixed to accomodate naming convention like Amazing Mary Jane (2019) 002.cbr, and to account for brackets properly
try:
while cnt < len(m):
#logger.fdebug('[m=%s] modfilename.find: %s' % (m[cnt], modfilename[modfilename.find('('+m[cnt]+')')+len(m[cnt])+2]))
#logger.fdebug('mod_1: %s' % modfilename.find('('+m[cnt]+')'))
if modfilename[modfilename.find('('+m[cnt]+')')-1] != modspacer and modfilename.find('('+m[cnt]+')') != -1:
#logger.fdebug('before_space: %s' % modfilename[modfilename.find('('+m[cnt]+')')-1])
#logger.fdebug('after_space: %s' % modfilename[modfilename.find('('+m[cnt]+')')+len(m[cnt])+2])
modfilename = '%s%s%s' % (modfilename[:modfilename.find('('+m[cnt]+')')], modspacer, modfilename[modfilename.find('('+m[cnt]+')'):])
cnt+=1
except Exception as e:
#logger.warn('[ERROR] %s' % e)
pass
#---end 2019-12-24
#grab the scanner tags here.
scangroup = None
rippers = [x for x in self.rippers if x.lower() in modfilename.lower()]
if rippers:
#it's always possible that this could grab something else since tags aren't unique. Try and figure it out.
if len(rippers) > 0:
m = re.findall('[^()]+', modfilename)
#--2019-11-30 needed for Glorith naming conventions when it's an nzb name with all formatting removed.
if len(m) == 1:
spf30 = re.compile(ur"[^.]+", re.UNICODE)
#logger.fdebug('spf30: %s' % spf30)
split_file30 = spf30.findall(modfilename)
#logger.fdebug('split_file30: %s' % split_file30)
if len(split_file30) > 3 and 'Glorith-HD' in modfilename:
scangroup = 'Glorith-HD'
sp_pos = 0
for x in split_file30:
if sp_pos+1 > len(split_file30):
break
if x[-1] == ',' and self.checkthedate(split_file30[sp_pos+1]):
modfilename = re.sub(x, x[:-1], modfilename, count=1)
break
sp_pos+=1
#-- end 2019-11-30
cnt = 1
for rp in rippers:
while cnt < len(m):
if m[cnt] == ' ':
pass
elif rp.lower() in m[cnt].lower():
scangroup = re.sub('[\(\)]', '', m[cnt]).strip()
logger.fdebug('Scanner group tag discovered: %s' % scangroup)
modfilename = modfilename.replace(m[cnt],'').strip()
break
cnt +=1
modfilename = modfilename.replace('()','').strip()
issueid = None
x = modfilename.find('[__')
if x != -1:
y = modfilename.find('__]', x)
if y != -1:
issueid = modfilename[x+3:y]
logger.fdebug('issueid: %s' % issueid)
modfilename = '%s %s'.strip() % (modfilename[:x], modfilename[y+3:])
logger.fdebug('issueid %s removed successfully: %s' % (issueid, modfilename))
#here we take a snapshot of the current modfilename, the intent is that we will remove characters that match
#as we discover them - namely volume, issue #, years, etc
#the remaining strings should be the series title and/or issue title if present (has to be detected properly)
modseries = modfilename
#try and remove /remember unicode character strings here (multiline ones get seperated/removed in below regex)
pat = re.compile(u'[\x00-\x7f]{3,}', re.UNICODE)
replack = pat.sub('XCV', modfilename)
wrds = replack.split('XCV')
tmpfilename = modfilename
if len(wrds) > 1:
for i in list(wrds):
if i != '':
tmpfilename = re.sub(i, 'XCV', tmpfilename)
tmpfilename = ''.join(tmpfilename)
modfilename = tmpfilename
sf3 = re.compile(ur"[^,\s_]+", re.UNICODE)
split_file3 = sf3.findall(modfilename)
#--2019-11-30
if len(split_file3) == 1 or all([len(split_file3) == 2, scangroup == 'Glorith-HD']):
#--end 2019-11-30
logger.fdebug('Improperly formatted filename - there is no seperation using appropriate characters between wording.')
sf3 = re.compile(ur"[^,\s_\.]+", re.UNICODE)
split_file3 = sf3.findall(modfilename)
logger.fdebug('NEW split_file3: %s' % split_file3)
ret_sf2 = ' '.join(split_file3)
sf = re.findall('''\( [^\)]* \) |\[ [^\]]* \] |\[ [^\#]* \]|\S+''', ret_sf2, re.VERBOSE)
#sf = re.findall('''\( [^\)]* \) |\[ [^\]]* \] |\S+''', ret_sf2, re.VERBOSE)
ret_sf1 = ' '.join(sf)
#here we should account for some characters that get stripped out due to the regex's
#namely, unique characters - known so far: +, &, @
#c11 = '\+'
#f11 = '\&'
#g11 = '\''
ret_sf1 = re.sub('\+', 'c11', ret_sf1).strip()
ret_sf1 = re.sub('\&', 'f11', ret_sf1).strip()
ret_sf1 = re.sub('\'', 'g11', ret_sf1).strip()
ret_sf1 = re.sub('\@', 'h11', ret_sf1).strip()
#split_file = re.findall('(?imu)\([\w\s-]+\)|[-+]?\d*\.\d+|\d+[\s]COVERS+|\d{4}-\d{2}-\d{2}|\d+[(th|nd|rd|st)]+|\d+|[\w-]+|#?\d\.\d+|#[\.-]\w+|#[\d*\.\d+|\w+\d+]+|#(?<![\w\d])XCV(?![\w\d])+|#[\w+]|\)', ret_sf1, re.UNICODE)
split_file = re.findall('(?imu)\([\w\s-]+\)|[-+]?\d*\.\d+|\d+[\s]COVERS+|\d{4}-\d{2}-\d{2}|\d+[(th|nd|rd|st)]+|[\(^\)+]|\d+|[\w-]+|#?\d\.\d+|#[\.-]\w+|#[\d*\.\d+|\w+\d+]+|#(?<![\w\d])XCV(?![\w\d])+|#[\w+]|\)', ret_sf1, re.UNICODE)
#10-20-2018 ---START -- attempt to detect '01 (of 7.3)'
#10-20-2018 -- attempt to detect '36p ctc' as one element
spf = []
mini = False
wrdcnt = 0
for x in split_file:
if x == 'of':
mini = True
spf.append(x)
elif mini is True:
mini = False
try:
logger.fdebug('checking now: %s' % x)
if x.lower() == 'infinity':
raise Exception
if x.isdigit():
logger.fdebug('[MINI-SERIES] MAX ISSUES IN SERIES: %s' % x)
spf.append('(of %s)' % x)
elif float(x) > 0:
logger.fdebug('[MINI-DECIMAL SERIES] MAX ISSUES IN SERIES: %s' % x)
spf.append('(of %s)' % x)
except Exception as e:
spf.append(x)
elif x == ')' or x == '(':
pass
elif x == 'p' or x == 'ctc':
try:
if spf[wrdcnt-1].isdigit():
logger.debug('THIS SHOULD BE : %s%s' % (spf[wrdcnt-1], x))
newline = '%s%s' % (spf[wrdcnt-1], x)
spf[wrdcnt -1] = newline
#wrdcnt =-1
elif spf[wrdcnt-1][-1] == 'p' and spf[wrdcnt-1][:-1].isdigit() and x == 'ctc':
logger.fdebug('THIS SHOULD BE : %s%s' % (spf[wrdcnt-1], x))
newline = '%s%s' % (spf[wrdcnt-1], x)
spf[wrdcnt -1] = newline
#wrdcnt =-1
except Exception as e:
spf.append(x)
else:
spf.append(x)
wrdcnt +=1
if len(spf) > 0:
split_file = spf
logger.fdebug('NEWLY SPLIT REORGD: %s' % split_file)
#10-20-2018 ---END
if len(split_file) == 1:
logger.fdebug('Improperly formatted filename - there is no seperation using appropriate characters between wording.')
ret_sf1 = re.sub('\-',' ', ret_sf1).strip()
split_file = re.findall('(?imu)\([\w\s-]+\)|[-+]?\d*\.\d+|\d+|[\w-]+|#?\d\.\d+|#(?<![\w\d])XCV(?![\w\d])+|\)', ret_sf1, re.UNICODE)
possible_issuenumbers = []
volumeprior = False
volume = None
volume_found = {}
datecheck = []
lastissue_label = None
lastissue_position = 0
lastmod_position = 0
booktype = 'issue'
#exceptions that are considered alpha-numeric issue numbers
exceptions = ('NOW', 'AI', 'AU', 'X', 'A', 'B', 'C', 'INH', 'MU', 'HU', 'SUMMER', 'SPRING', 'FALL', 'WINTER', 'PREVIEW')
#unicode characters, followed by int value
# num_exceptions = [{iss:u'\xbd',val:.5},{iss:u'\xbc',val:.25}, {iss:u'\xe',val:.75}, {iss:u'\221e',val:'infinity'}]
file_length = 0
validcountchk = False
sep_volume = False
current_pos = -1
for sf in split_file:
current_pos +=1
#the series title will always be first and be AT LEAST one word.
if split_file.index(sf) >= 0 and not volumeprior:
dtcheck = re.sub('[\(\)\,]', '', sf).strip()
#if there's more than one date, assume the right-most date is the actual issue date.
if any(['19' in dtcheck, '20' in dtcheck]) and not any([dtcheck.lower().startswith('v19'), dtcheck.lower().startswith('v20')]) and len(dtcheck) >=4:
logger.fdebug('checking date : %s' % dtcheck)
checkdate_response = self.checkthedate(dtcheck)
if checkdate_response:
logger.fdebug('date: %s' % checkdate_response)
datecheck.append({'date': dtcheck,
'position': split_file.index(sf),
'mod_position': self.char_file_position(modfilename, sf, lastmod_position)})
#this handles the exceptions list in the match for alpha-numerics
test_exception = ''.join([i for i in sf if not i.isdigit()])
if any([x for x in exceptions if x.lower() == test_exception.lower()]):
logger.fdebug('Exception match: %s' % test_exception)
if lastissue_label is not None:
if lastissue_position == (split_file.index(sf) -1):
logger.fdebug('alphanumeric issue number detected as : %s %s' % (lastissue_label,sf))
for x in possible_issuenumbers:
possible_issuenumbers = []
if int(x['position']) != int(lastissue_position):
possible_issuenumbers.append({'number': x['number'],
'position': x['position'],
'mod_position': x['mod_position'],
'validcountchk': x['validcountchk']})
possible_issuenumbers.append({'number': '%s %s' % (lastissue_label, sf),
'position': lastissue_position,
'mod_position': self.char_file_position(modfilename, sf, lastmod_position),
'validcountchk': validcountchk})
else:
#if the issue number & alpha character(s) don't have a space seperating them (ie. 15A)
#test_exception is the alpha-numeric
logger.fdebug('Possible alpha numeric issue (or non-numeric only). Testing my theory.')
test_sf = re.sub(test_exception.lower(), '', sf.lower()).strip()
logger.fdebug('[%s] Removing possible alpha issue leaves: %s (Should be a numeric)' % (test_exception, test_sf))
if test_sf.isdigit():
possible_issuenumbers.append({'number': sf,
'position': split_file.index(sf),
'mod_position': self.char_file_position(modfilename, sf, lastmod_position),
'validcountchk': validcountchk})
else:
test_position = modfilename[self.char_file_position(modfilename, sf,lastmod_position)-1]
if test_position == '#':
possible_issuenumbers.append({'number': sf,
'position': split_file.index(sf),
'mod_position': self.char_file_position(modfilename, sf, lastmod_position),
'validcountchk': validcountchk})
if sf == 'XCV':
# new 2016-09-19 \ attempt to check for XCV which replaces any unicode above
for x in list(wrds):
if x != '':
tmpissue_number = re.sub('XCV', x, split_file[split_file.index(sf)])
logger.info('[SPECIAL-CHARACTER ISSUE] Possible issue # : %s' % tmpissue_number)
possible_issuenumbers.append({'number': sf,
'position': split_file.index(sf),
'mod_position': self.char_file_position(modfilename, sf, lastmod_position),
'validcountchk': validcountchk})
count = None
found = False
match = re.search('(?<=\sof\s)\d+(?=\s)', sf, re.IGNORECASE)
if match:
logger.fdebug('match')
count = match.group()
found = True
if found is False:
match = re.search('(?<=\(of\s)\d+(?=\))', sf, re.IGNORECASE)
if match:
count = match.group()
found = True
if count:
# count = count.lstrip("0")
logger.fdebug('Mini-Series Count detected. Maximum issue # set to : %s' % count.lstrip('0'))
# if the count was detected, then it's in a '(of 4)' or whatever pattern
# 95% of the time the digit immediately preceding the '(of 4)' is the actual issue #
logger.fdebug('Issue Number SHOULD BE: %s' % lastissue_label)
validcountchk = True
match2 = re.search('(\d+[\s])covers', sf, re.IGNORECASE)
if match2:
num_covers = re.sub('[^0-9]', '', match2.group()).strip()
#logger.fdebug('%s covers detected within filename' % num_covers)
continue
if all([lastissue_position == (split_file.index(sf) -1), lastissue_label is not None, '#' not in sf, sf != 'p']):
#find it in the original file to see if there's a decimal between.
findst = lastissue_mod_position+1
if findst >= len(modfilename):
findst = len(modfilename) -1
if modfilename[findst] != '.' or modfilename[findst] != '#': #findst != '.' and findst != '#':
if sf.isdigit():
seper_num = False
for x in datecheck:
if x['position'] == split_file.index(sf, lastissue_position):
seper_num = True
if seper_num is False:
logger.fdebug('2 seperate numbers detected. Assuming 2nd number is the actual issue')
#possible_issuenumbers.append({'number': sf,
# 'position': split_file.index(sf, lastissue_position), #modfilename.find(sf)})
# 'mod_position': self.char_file_position(modfilename, sf, lastmod_position),
# 'validcountchk': validcountchk})
#used to see if the issue is an alpha-numeric (ie. 18.NOW, 50-X, etc)
lastissue_position = split_file.index(sf, lastissue_position)
lastissue_label = sf
lastissue_mod_position = file_length
else:
pass
else:
bb = len(lastissue_label) + findst
#find current sf
#logger.fdebug('bb: ' + str(bb) + '[' + modfilename[findst:bb] + ']')
cf = modfilename.find(sf, file_length)
#logger.fdebug('cf: ' + str(cf) + '[' + modfilename[cf:cf+len(sf)] + ']')
diff = bb
#logger.fdebug('diff: ' + str(bb) + '[' + modfilename[bb] + ']')
if modfilename[bb] == '.':
#logger.fdebug('decimal detected.')
logger.fdebug('[DECiMAL-DETECTION] Issue being stored for validation as : %s' % modfilename[findst:cf+len(sf)])
for x in possible_issuenumbers:
possible_issuenumbers = []
#logger.fdebug('compare: ' + str(x['position']) + ' .. ' + str(lastissue_position))
#logger.fdebug('compare: ' + str(x['position']) + ' .. ' + str(split_file.index(sf, lastissue_position)))
if int(x['position']) != int(lastissue_position) and int(x['position']) != split_file.index(sf, lastissue_position):
possible_issuenumbers.append({'number': x['number'],
'position': x['position'],
'mod_position': x['mod_position'],
'validcountchk': x['validcountchk']})
possible_issuenumbers.append({'number': modfilename[findst:cf+len(sf)],
'position': split_file.index(lastissue_label, lastissue_position),
'mod_position': findst,
'dec_position': bb,
'rem_position': split_file.index(sf),
'validcountchk': validcountchk})
else:
if ('#' in sf or sf.isdigit()) or validcountchk:
if validcountchk:
#if it's not a decimal but the digits are back-to-back, then it's something else.
possible_issuenumbers.append({'number': lastissue_label,
'position': lastissue_position,
'mod_position': lastissue_mod_position,
'validcountchk': validcountchk})
validcountchk = False
#used to see if the issue is an alpha-numeric (ie. 18.NOW, 50-X, etc)
lastissue_position = split_file.index(sf, lastissue_position)
lastissue_label = sf
lastissue_mod_position = file_length
elif '#' in sf:
logger.fdebug('Issue number found: %s' % sf)
#pound sign will almost always indicate an issue #, so just assume it's as such.
locateiss_st = modfilename.find('#')
locateiss_end = modfilename.find(' ', locateiss_st)
if locateiss_end == -1:
locateiss_end = len(modfilename)
if modfilename[locateiss_end-1] == ')':
locateiss_end = locateiss_end -1
possible_issuenumbers.append({'number': modfilename[locateiss_st:locateiss_end],
'position': split_file.index(sf), #locateiss_st})
'mod_position': self.char_file_position(modfilename, sf, lastmod_position),
'validcountchk': validcountchk})
#now we try to find the series title &/or volume lablel.
if any( [sf.lower().startswith('v'), sf.lower().startswith('vol'), volumeprior == True, 'volume' in sf.lower(), 'vol' in sf.lower(), 'part' in sf.lower()] ) and sf.lower() not in {'one','two','three','four','five','six'}:
if any([ split_file[split_file.index(sf)].isdigit(), split_file[split_file.index(sf)][3:].isdigit(), split_file[split_file.index(sf)][1:].isdigit() ]):
if all(identifier in sf for identifier in ['.', 'v']):
volume = sf.split('.')[0]
else:
volume = re.sub("[^0-9]", "", sf)
if volumeprior:
try:
volume_found['position'] = split_file.index(volumeprior_label, current_pos -1) #if this passes, then we're ok, otherwise will try exception
logger.fdebug('volume_found: %s' % volume_found['position'])
#remove volume numeric from split_file
split_file.pop(volume_found['position'])
split_file.pop(split_file.index(sf, current_pos-1))
#join the previous label to the volume numeric
#volume = str(volumeprior_label) + str(volume)
#insert the combined info back
split_file.insert(volume_found['position'], volumeprior_label + volume)
split_file.insert(volume_found['position']+1, '')
#volume_found['position'] = split_file.index(sf, current_pos)
#logger.fdebug('NEWSPLITFILE: %s' % split_file)
except:
volumeprior = False
volumeprior_label = None
sep_volume = False
continue
else:
volume_found['position'] = split_file.index(sf, current_pos)
volume_found['volume'] = volume
logger.fdebug('volume label detected as : Volume %s @ position: %s' % (volume, volume_found['position']))
volumeprior = False
volumeprior_label = None
elif all(['vol' in sf.lower(), len(sf) == 3]) or all(['vol.' in sf.lower(), len(sf) == 4]):
#if there's a space between the vol and # - adjust.
volumeprior = True
volumeprior_label = sf
sep_volume = True
logger.fdebug('volume label detected, but vol. number is not adjacent, adjusting scope to include number.')
elif 'volume' in sf.lower() or all(['part' in sf.lower(), len(sf) == 4]):
volume = re.sub("[^0-9]", "", sf)
if volume.isdigit():
volume_found['volume'] = volume
volume_found['position'] = split_file.index(sf)
else:
volumeprior = True
volumeprior_label = sf
sep_volume = True
elif any([sf == 'I', sf == 'II', sf == 'III', sf == 'IV']) and volumeprior:
volumeprior = False
volumeprior_label = None
sep_volume = False
continue
else:
#reset the sep_volume indicator here in case a false Volume detected above
sep_volume = False
#check here for numeric or negative number
if sf.isdigit() and split_file.index(sf, current_pos) == 0:
continue
if sf.isdigit():
possible_issuenumbers.append({'number': sf,
'position': split_file.index(sf, current_pos), #modfilename.find(sf)})
'mod_position': self.char_file_position(modfilename, sf, lastmod_position),
'validcountchk': validcountchk})
#used to see if the issue is an alpha-numeric (ie. 18.NOW, 50-X, etc)
lastissue_position = split_file.index(sf, current_pos)
lastissue_label = sf
lastissue_mod_position = file_length
#logger.fdebug('possible issue found: %s' % sf)
else:
try:
x = float(sf)
#validity check
if x < 0:
logger.fdebug('I have encountered a negative issue #: %s' % sf)
possible_issuenumbers.append({'number': sf,
'position': split_file.index(sf, lastissue_position), #modfilename.find(sf)})
'mod_position': self.char_file_position(modfilename, sf, lastmod_position),
'validcountchk': validcountchk})
lastissue_position = split_file.index(sf, lastissue_position)
lastissue_label = sf
lastissue_mod_position = file_length
elif x > 0:
logger.fdebug('I have encountered a decimal issue #: %s' % sf)
possible_issuenumbers.append({'number': sf,
'position': split_file.index(sf, lastissue_position), #modfilename.find(sf)})
'mod_position': self.char_file_position(modfilename, sf, lastmod_position),
'validcountchk': validcountchk})
lastissue_position = split_file.index(sf, lastissue_position)
lastissue_label = sf
lastissue_mod_position = file_length
else:
raise ValueError
except ValueError, e:
#10-20-2018 - to detect issue numbers such as #000.0000½
if lastissue_label is not None and lastissue_position == int(split_file.index(sf))-1 and sf == 'XCV':
logger.info('this should be: %s%s' % (lastissue_label, sf))
pi = []
for x in possible_issuenumbers:
if (x['number'] == lastissue_label and x['position'] == lastissue_position) or (x['number'] == sf and x['position'] == split_file.index(sf, lastissue_position)):
pass
else:
pi.append({'number': x['number'],
'position': x['position'],
'mod_position': x['mod_position'],
'validcountchk': x['validcountchk']})
lastissue_label = '%s%s' % (lastissue_label, sf)
pi.append({'number': lastissue_label,
'position': lastissue_position,
'mod_position': lastmod_position,
'validcountchk': validcountchk})
if len(pi) > 0:
possible_issuenumbers = pi
elif sf.lower() == 'of' and lastissue_label is not None and lastissue_position == int(split_file.index(sf))-1:
logger.info('MINI-SERIES DETECTED')
else:
if any([re.sub('[\(\)]', '', sf.lower()).strip() == 'tpb', re.sub('[\(\)]', '', sf.lower()).strip() == 'digital tpb']):
logger.info('TRADE PAPERBACK DETECTED. NOT DETECTING ISSUE NUMBER - ASSUMING VOLUME')
booktype = 'TPB'
try:
if volume_found['volume'] is not None:
possible_issuenumbers.append({'number': volume_found['volume'],
'position': volume_found['position'],
'mod_position': self.char_file_position(modfilename, volume_found['volume'], lastmod_position),
'validcountchk': validcountchk})
except:
possible_issuenumbers.append({'number': '1',
'position': split_file.index(sf, lastissue_position), #modfilename.find(sf)})
'mod_position': self.char_file_position(modfilename, sf, lastmod_position),
'validcountchk': validcountchk})
elif any([sf.lower() == 'gn', sf.lower() == 'graphic novel']):
logger.info('GRAPHIC NOVEL DETECTED. NOT DETECTING ISSUE NUMBER - ASSUMING VOLUME')
booktype = 'GN'
else:
if 'could not convert string to float' not in str(e):
logger.fdebug('[%s] Error detecting issue # - ignoring this result : %s' % (e, sf))
volumeprior = False
volumeprior_label = None
sep_volume = False
pass
#keep track of where in the original modfilename the positions are in order to check against it for decimal places, etc.
file_length += len(sf) + 1 #1 for space
if file_length > len(modfilename):
file_length = len(modfilename)
lastmod_position = self.char_file_position(modfilename, sf, lastmod_position)
highest_series_pos = len(split_file)
issue2year = False
issue_year = None
possible_years = []
yearmodposition = None
logger.fdebug('datecheck: %s' % datecheck)
if len(datecheck) > 0:
for dc in sorted(datecheck, key=operator.itemgetter('position'), reverse=True):
a = self.checkthedate(dc['date'])
ab = str(a)
sctd = self.checkthedate(str(dt.datetime.now().year))
logger.fdebug('sctd: %s' % sctd)
# + 1 sctd so that we can allow for issue dates that cross over into the following year when it's nearer to the end of said year.
if int(ab) > int(sctd) + 1:
logger.fdebug('year is in the future, ignoring and assuming part of series title.')
yearposition = None
yearmodposition = None
continue
else:
issue_year = dc['date']
logger.fdebug('year verified as : %s' % issue_year)
if highest_series_pos > dc['position']: highest_series_pos = dc['position']
yearposition = dc['position']
yearmodposition = dc['mod_position']
if len(ab) == 4:
issue_year = ab
logger.fdebug('year verified as: %s' % issue_year)
possible_years.append({'year': issue_year,
'yearposition': dc['position'],
'yearmodposition': dc['mod_position']})
else:
issue_year = ab
logger.fdebug('date verified as: %s' % issue_year)
if len(possible_years) == 1:
issueyear = possible_years[0]['year']
yearposition = possible_years[0]['yearposition']
yearmodposition = possible_years[0]['yearmodposition']
else:
if len(possible_issuenumbers) > 0:
for x in possible_years:
logger.info('yearposition[%s] -- dc[position][%s]' % (yearposition, x['yearposition']))
if yearposition < x['yearposition']:
if all([len(possible_issuenumbers) == 1, possible_issuenumbers[0]['number'] == x['year'], x['yearposition'] != possible_issuenumbers[0]['position']]):
issue2year = True
highest_series_pos = x['yearposition']
yearposition = x['yearposition']
yearmodposition = x['yearmodposition']
if yearposition is not None and highest_series_pos > yearposition:
highest_series_pos = yearposition #dc['position']: highest_series_pos = dc['position']
else:
issue_year = None
yearposition = None
yearmodposition = None
logger.fdebug('No year present within title - ignoring as a variable.')
logger.fdebug('highest_series_position: %s' % highest_series_pos)
#---2019-11-30 account for scanner Glorith-HD stupid naming conventions
if len(possible_issuenumbers) == 0 and scangroup == 'Glorith-HD':
logger.fdebug('Abnormal formatting detected. Time to fix this shiet, yo.')
if any([yearposition == 0, yearposition is None]):
logger.fdebug('Too stupid of a format. Nope. Not gonna happen - just reinvent the wheel you fooker.')
else:
issposs = yearposition + 1
#logger.fdebug('split_file: %s' % split_file[issposs])
if '(' and ')' in split_file[issposs]:
new_issuenumber = split_file[issposs]
possible_issuenumbers.append({'number': re.sub('[/(/)]', '', split_file[issposs]).strip(),
'position': split_file.index(new_issuenumber, yearposition),
'mod_position': self.char_file_position(modfilename, new_issuenumber, yearmodposition),
'validcountchk': False})
#---end 2019-11-30
issue_number = None
dash_numbers = []
issue_number_position = len(split_file)
if len(possible_issuenumbers) > 0:
logger.fdebug('possible_issuenumbers: %s' % possible_issuenumbers)
if len(possible_issuenumbers) >= 1:
p = 1
if '-' not in split_file[0]:
finddash = modfilename.find('-')
if finddash != -1:
logger.fdebug('hyphen located at position: %s' % finddash)
if yearposition:
logger.fdebug('yearposition: %s' % yearposition)
else:
finddash = -1
logger.fdebug('dash is in first word, not considering for determing issue number.')
for pis in sorted(possible_issuenumbers, key=operator.itemgetter('position'), reverse=True):
a = ' '.join(split_file)
lenn = pis['mod_position'] + len(pis['number'])
if lenn == len(a) and finddash != -1:
logger.fdebug('Numeric detected as the last digit after a hyphen. Typically this is the issue number.')
if pis['position'] != yearposition:
issue_number = pis['number']
#logger.info('Issue set to: ' + str(issue_number))
issue_number_position = pis['position']
if highest_series_pos > pis['position']: highest_series_pos = pis['position']
#break
elif pis['validcountchk'] == True:
issue_number = pis['number']
issue_number_position = pis['position']
logger.fdebug('Issue verified and detected as part of a numeric count sequnce: %s' % issue_number)
if highest_series_pos > pis['position']: highest_series_pos = pis['position']
break
elif pis['mod_position'] > finddash and finddash != -1:
if finddash < yearposition and finddash > (yearmodposition + len(split_file[yearposition])):
logger.fdebug('issue number is positioned after a dash - probably not an issue number, but part of an issue title')
dash_numbers.append({'mod_position': pis['mod_position'],
'number': pis['number'],
'position': pis['position']})
continue
#2019-10-05 fix - if decimal-spaced filename has a series title with a hyphen will include issue # as part of series title
elif yearposition == pis['position']:
logger.info('Already validated year, ignoring as possible issue number: %s' % pis['number'])
continue
#end 2019-10-05
elif yearposition == pis['position']:
logger.fdebug('Already validated year, ignoring as possible issue number: %s' % pis['number'])
continue
if p == 1:
issue_number = pis['number']
issue_number_position = pis['position']
logger.fdebug('issue number :%s' % issue_number) #(pis)
if highest_series_pos > pis['position'] and issue2year is False: highest_series_pos = pis['position']
#else:
#logger.fdebug('numeric probably belongs to series title: ' + str(pis))
p+=1
else:
issue_number = possible_issuenumbers[0]['number']
issue_number_position = possible_issuenumbers[0]['position']
if highest_series_pos > possible_issuenumbers[0]['position']: highest_series_pos = possible_issuenumbers[0]['position']
if issue_number:
issue_number = re.sub('#', '', issue_number).strip()
else:
if len(dash_numbers) > 0 and finddash !=-1 :
#there are numbers after a dash, which was incorrectly accounted for.
fin_num_position = finddash
fin_num = None
for dn in dash_numbers:
if dn['mod_position'] > finddash and dn['mod_position'] > fin_num_position:
fin_num_position = dn['mod_position']
fin_num = dn['number']
fin_pos = dn['position']
if fin_num:
logger.fdebug('Issue number re-corrected to : %s' % fin_num)
issue_number = fin_num
if highest_series_pos > fin_pos: highest_series_pos = fin_pos
#--- this is new - 2016-09-18 /account for unicode in issue number when issue number is not deteted above
logger.fdebug('issue_position: %s' % issue_number_position)
if all([issue_number_position == highest_series_pos, 'XCV' in split_file, issue_number is None]):
for x in list(wrds):
if x != '':
issue_number = re.sub('XCV', x, split_file[issue_number_position-1])
highest_series_pos -=1
issue_number_position -=1
if issue_number is None:
if any([booktype == 'TPB', booktype == 'GN']):
logger.info('%s detected. Volume assumption is number: %s' % (booktype, volume_found))
else:
if len(volume_found) > 0:
logger.info('UNKNOWN TPB/GN detected. Volume assumption is number: %s' % (volume_found))
else:
logger.info('No issue number present in filename.')
else:
logger.fdebug('issue verified as : %s' % issue_number)
issue_volume = None
if len(volume_found) > 0:
issue_volume = 'v' + str(volume_found['volume'])
if all([highest_series_pos + 1 != volume_found['position'], highest_series_pos != volume_found['position'] + 1, sep_volume == False, booktype == 'issue', len(possible_issuenumbers) > 0]):
logger.fdebug('Extra item(s) are present between the volume label and the issue number. Checking..')
split_file.insert(int(issue_number_position), split_file.pop(volume_found['position'])) #highest_series_pos-1, split_file.pop(volume_found['position']))
logger.fdebug('new split: %s' % split_file)
highest_series_pos = volume_found['position'] -1
#2019-10-02 - account for volume BEFORE issue number
if issue_number_position > highest_series_pos:
issue_number_position -=1
else:
if highest_series_pos > volume_found['position']:
if sep_volume:
highest_series_pos = volume_found['position'] - 1
else:
highest_series_pos = volume_found['position']
logger.fdebug('Volume detected as : %s' % issue_volume)
if all([len(volume_found) == 0, booktype != 'issue']) or all([len(volume_found) == 0, issue_number_position == len(split_file)]):
issue_volume = 'v1'
#at this point it should be in a SERIES ISSUE VOLUME YEAR kind of format
#if the position of the issue number is greater than the highest series position, make it the highest series position.
if issue_number_position != len(split_file) and issue_number_position > highest_series_pos:
if not volume_found:
highest_series_pos = issue_number_position
else:
if sep_volume:
highest_series_pos = issue_number_position -2
else:
if split_file[issue_number_position -1].lower() == 'annual' or split_file[issue_number_position -1].lower() == 'special':
highest_series_pos = issue_number_position
else:
highest_series_pos = issue_number_position - 1
#if volume_found['position'] < issue_number_position:
# highest_series_pos = issue_number_position - 1
#else:
# highest_series_pos = issue_number_position
#make sure if we have multiple years detected, that the right one gets picked for the actual year vs. series title
if len(possible_years) > 1:
for x in sorted(possible_years, key=operator.itemgetter('yearposition'), reverse=False):
if x['yearposition'] <= highest_series_pos:
logger.fdebug('year %s is within series title. Ignoring as YEAR value' % x['year'])
else:
logger.fdebug('year %s is outside of series title range. Accepting of year.' % x['year'])
issue_year = x['year']
highest_series_pos = x['yearposition']
break
else:
try:
if possible_years[0]['yearposition'] <= highest_series_pos and possible_years[0]['year_position'] != 0:
highest_series_pos = possible_years[0]['yearposition']
elif possible_years[0]['year_position'] == 0:
yearposition = 1
except:
pass
match_type = None #folder/file based on how it was matched.
#logger.fdebug('highest_series_pos is : ' + str(highest_series_pos)
splitvalue = None
alt_series = None
alt_issue = None
try:
if yearposition is not None:
try:
if volume_found['position'] >= issue_number_position:
tmpval = highest_series_pos + (issue_number_position - volume_found['position'])
else:
tmpval = yearposition - issue_number_position
except:
tmpval = yearposition - issue_number_position
else:
tmpval = 1
except:
pass
else:
if tmpval > 2:
logger.fdebug('There are %s extra words between the issue # and the year position. Deciphering if issue title or part of series title.' % tmpval)
tmpval1 = ' '.join(split_file[issue_number_position:yearposition])
if split_file[issue_number_position+1] == '-':
usevalue = ' '.join(split_file[issue_number_position+2:yearposition])
splitv = split_file[issue_number_position+2:yearposition]
else:
splitv = split_file[issue_number_position:yearposition]
splitvalue = ' '.join(splitv)
else:
#store alternate naming of title just in case
if '-' not in split_file[0]:
c_pos = 1
#logger.info('split_file: %s' % split_file)
while True:
try:
fdash = split_file.index("-", c_pos)
except:
#logger.info('dash not located/finished searching for dashes.')
break
else:
#logger.info('hyphen located at position: ' + str(fdash))
c_pos = 2
#c_pos = fdash +1
break
if c_pos > 1:
#logger.info('Issue_number_position: %s / fdash: %s' % (issue_number_position, fdash))
try:
if volume_found['position'] < issue_number_position:
alt_issue = ' '.join(split_file[fdash+1:volume_found['position']])
else:
alt_issue = ' '.join(split_file[fdash+1:issue_number_position])
except:
alt_issue = ' '.join(split_file[fdash+1:issue_number_position])
if alt_issue.endswith('-'): alt_issue = alt_issue[:-1].strip()
if len(alt_issue) == 0:
alt_issue = None
alt_series = ' '.join(split_file[:fdash])
logger.fdebug('ALT-SERIES NAME [ISSUE TITLE]: %s [%s]' % (alt_series, alt_issue))
#logger.info('highest_series_position: ' + str(highest_series_pos))
#logger.info('issue_number_position: ' + str(issue_number_position))
#logger.info('volume_found: ' + str(volume_found))
#2017-10-21
if highest_series_pos > issue_number_position:
highest_series_pos = issue_number_position
#if volume_found['position'] >= issue_number_position:
# highest_series_pos = issue_number_position
#else:
# print 'nuhuh'
#---
match_type = None #folder/file based on how it was matched.
logger.fdebug('sf_highest_series_pos: %s' % split_file[:highest_series_pos])
#here we should account for some characters that get stripped out due to the regex's
#namely, unique characters - known so far: +
#c1 = '+'
#series_name = ' '.join(split_file[:highest_series_pos])
if yearposition != 0:
if yearposition is not None and yearposition < highest_series_pos:
if yearposition+1 == highest_series_pos:
highest_series_pos = yearposition
else:
if split_file[yearposition+1] == '-' and yearposition+2 == highest_series_pos:
highest_series_pos = yearposition
series_name = ' '.join(split_file[:highest_series_pos])
else:
if highest_series_pos <= issue_number_position and all([len(split_file[0]) == 4, split_file[0].isdigit()]):
series_name = ' '.join(split_file[:highest_series_pos])
else:
series_name = ' '.join(split_file[yearposition+1:highest_series_pos])
for x in list(wrds):
if x != '':
if 'XCV' in series_name:
series_name = re.sub('XCV', x, series_name,1)
elif 'XCV' in issue_number:
issue_number = re.sub('XCV', x, issue_number,1)
if alt_series is not None:
if 'XCV' in alt_series:
alt_series = re.sub('XCV', x, alt_series,1)
if alt_issue is not None:
if 'XCV' in alt_issue:
alt_issue = re.sub('XCV', x, alt_issue,1)
series_name = re.sub('c11', '+', series_name)
series_name = re.sub('f11', '&', series_name)
series_name = re.sub('g11', '\'', series_name)
series_name = re.sub('h11', '@', series_name)
if alt_series is not None:
alt_series = re.sub('c11', '+', alt_series)
alt_series = re.sub('f11', '&', alt_series)
alt_series = re.sub('g11', '\'', alt_series)
alt_series = re.sub('h11', '@', alt_series)
if series_name.endswith('-'):
series_name = series_name[:-1].strip()
if '\?' in series_name:
series_name = re.sub('\?', '', series_name).strip()
logger.fdebug('series title possibly: %s' % series_name)
if splitvalue is not None:
logger.fdebug('[SPLITVALUE] possible issue title: %s' % splitvalue)
alt_series = '%s %s' % (series_name, splitvalue)
if booktype != 'issue':
if alt_issue is not None:
alt_issue = re.sub('tpb', '', splitvalue, flags=re.I).strip()
if alt_series is not None:
alt_series = re.sub('tpb', '', alt_series, flags=re.I).strip()
if alt_series is not None:
if booktype != 'issue':
if alt_series is not None:
alt_series = re.sub('tpb', '', alt_series, flags=re.I).strip()
logger.fdebug('Alternate series / issue title: %s [%s]' % (alt_series, alt_issue))
#if the filename is unicoded, it won't match due to the unicode translation. Keep the unicode as well as the decoded.
series_name_decoded= unicodedata.normalize('NFKD', helpers.conversion(series_name)).encode('ASCII', 'ignore')
#check for annual in title(s) here.
if not self.justparse and all([mylar.CONFIG.ANNUALS_ON, 'annual' not in self.watchcomic.lower(), 'special' not in self.watchcomic.lower()]):
if 'annual' in series_name.lower():
isn = 'Annual'
if issue_number is not None:
issue_number = '%s %s' % (isn, issue_number)
else:
issue_number = isn
series_name = re.sub('annual', '', series_name, flags=re.I).strip()
series_name_decoded = re.sub('annual', '', series_name_decoded, flags=re.I).strip()
elif 'special' in series_name.lower():
isn = 'Special'
if issue_number is not None:
issue_number = '%s %s' % (isn, issue_number)
else:
issue_number = isn
series_name = re.sub('special', '', series_name, flags=re.I).strip()
series_name_decoded = re.sub('special', '', series_name_decoded, flags=re.I).strip()
if (any([issue_number is None, series_name is None]) and booktype == 'issue'):
if all([issue_number is None, booktype == 'issue', issue_volume is not None]):
logger.info('Possible UKNOWN TPB/GN detected - no issue number present, no clarification in filename, but volume present with series title')
else:
logger.fdebug('Cannot parse the filename properly. I\'m going to make note of this filename so that my evil ruler can make it work.')
if series_name is not None:
dreplace = self.dynamic_replace(series_name)['mod_seriesname']
else:
dreplace = None
return {'parse_status': 'failure',
'sub': path_list,
'comicfilename': filename,
'comiclocation': self.dir,
'series_name': series_name,
'series_name_decoded': series_name_decoded,
'issueid': issueid,
'alt_series': alt_series,
'alt_issue': alt_issue,
'dynamic_name': dreplace,
'issue_number': issue_number,
'justthedigits': issue_number, #redundant but it's needed atm
'series_volume': issue_volume,
'issue_year': issue_year,
'annual_comicid': None,
'scangroup': scangroup,
'booktype': booktype,
'reading_order': None}
if self.justparse:
return {'parse_status': 'success',
'type': re.sub('\.','', filetype).strip(),
'sub': path_list,
'comicfilename': filename,
'comiclocation': self.dir,
'series_name': series_name,
'series_name_decoded': series_name_decoded,
'issueid': issueid,
'alt_series': alt_series,
'alt_issue': alt_issue,
'dynamic_name': self.dynamic_replace(series_name)['mod_seriesname'],
'series_volume': issue_volume,
'issue_year': issue_year,
'issue_number': issue_number,
'scangroup': scangroup,
'booktype': booktype,
'reading_order': reading_order}
series_info = {}
series_info = {'sub': path_list,
'type': re.sub('\.','', filetype).strip(),
'comicfilename': filename,
'comiclocation': self.dir,
'series_name': series_name,
'series_name_decoded': series_name_decoded,
'issueid': issueid,
'alt_series': alt_series,
'alt_issue': alt_issue,
'series_volume': issue_volume,
'issue_year': issue_year,
'issue_number': issue_number,
'scangroup': scangroup,
'booktype': booktype}
return self.matchIT(series_info)
def matchIT(self, series_info):
series_name = series_info['series_name']
alt_series = series_info['alt_series']
filename = series_info['comicfilename']
#compare here - match comparison against u_watchcomic.
#logger.fdebug('Series_Name: ' + series_name + ' --- WatchComic: ' + self.watchcomic)
#check for dynamic handles here.
mod_dynamicinfo = self.dynamic_replace(series_name)
mod_seriesname = mod_dynamicinfo['mod_seriesname']
mod_watchcomic = mod_dynamicinfo['mod_watchcomic']
mod_altseriesname = None
mod_altseriesname_decoded = None
#logger.fdebug('series_info: %s' % series_info)
if series_info['alt_series'] is not None:
mod_dynamicalt = self.dynamic_replace(alt_series)
mod_altseriesname = mod_dynamicalt['mod_seriesname']
mod_alt_decoded = self.dynamic_replace(alt_series)
mod_altseriesname_decoded = mod_alt_decoded['mod_seriesname']
#logger.fdebug('mod_altseriesname: %s' % mod_altseriesname)
mod_series_decoded = self.dynamic_replace(series_info['series_name_decoded'])
mod_seriesname_decoded = mod_series_decoded['mod_seriesname']
mod_watch_decoded = self.dynamic_replace(self.og_watchcomic)
mod_watchname_decoded = mod_watch_decoded['mod_watchcomic']
#remove the spaces...
nspace_seriesname = re.sub(' ', '', mod_seriesname)
nspace_watchcomic = re.sub(' ', '', mod_watchcomic)
nspace_altseriesname = None
if mod_altseriesname is not None:
nspace_altseriesname = re.sub(' ', '', mod_altseriesname)
nspace_altseriesname_decoded = re.sub(' ', '', mod_altseriesname_decoded)
nspace_seriesname_decoded = re.sub(' ', '', mod_seriesname_decoded)
nspace_watchname_decoded = re.sub(' ', '', mod_watchname_decoded)
try:
if self.AS_ALT[0] != '127372873872871091383 abdkhjhskjhkjdhakajhf':
logger.fdebug('Possible Alternate Names to match against (if necessary): %s' % self.AS_Alt)
except:
pass
justthedigits = series_info['issue_number']
if mylar.CONFIG.ANNUALS_ON and 'annual' not in nspace_watchcomic.lower():
if 'annual' in series_name.lower():
justthedigits = 'Annual'
if series_info['issue_number'] is not None:
justthedigits += ' %s' % series_info['issue_number']
nspace_seriesname = re.sub('annual', '', nspace_seriesname.lower()).strip()
nspace_seriesname_decoded = re.sub('annual', '', nspace_seriesname_decoded.lower()).strip()
if alt_series is not None and 'annual' in alt_series.lower():
nspace_altseriesname = re.sub('annual', '', nspace_altseriesname.lower()).strip()
nspace_altseriesname_decoded = re.sub('annual', '', nspace_altseriesname_decoded.lower()).strip()
if mylar.CONFIG.ANNUALS_ON and 'special' not in nspace_watchcomic.lower():
if 'special' in series_name.lower():
justthedigits = 'Special'
if series_info['issue_number'] is not None:
justthedigits += ' %s' % series_info['issue_number']
nspace_seriesname = re.sub('special', '', nspace_seriesname.lower()).strip()
nspace_seriesname_decoded = re.sub('special', '', nspace_seriesname_decoded.lower()).strip()
if alt_series is not None and 'special' in alt_series.lower():
nspace_altseriesname = re.sub('special', '', nspace_altseriesname.lower()).strip()
nspace_altseriesname_decoded = re.sub('special', '', nspace_altseriesname_decoded.lower()).strip()
seriesalt = False
if nspace_altseriesname is not None:
if re.sub('\|','', nspace_altseriesname.lower()).strip() == re.sub('\|', '', nspace_watchcomic.lower()).strip():
seriesalt = True
if any([seriesalt is True, re.sub('\|','', nspace_seriesname.lower()).strip() == re.sub('\|', '', nspace_watchcomic.lower()).strip(), re.sub('\|','', nspace_seriesname_decoded.lower()).strip() == re.sub('\|', '', nspace_watchname_decoded.lower()).strip()]) or any(re.sub('[\|\s]','', x.lower()).strip() == re.sub('[\|\s]','', nspace_seriesname.lower()).strip() for x in self.AS_Alt):
#logger.fdebug('[MATCH: ' + series_info['series_name'] + '] ' + filename)
enable_annual = False
annual_comicid = None
if any(re.sub('[\|\s]','', x.lower()).strip() == re.sub('[\|\s]','', nspace_seriesname.lower()).strip() for x in self.AS_Alt):
#if the alternate search name is almost identical, it won't match up because it will hit the 'normal' first.
#not important for series' matches, but for annuals, etc it is very important.
#loop through the Alternates picking out the ones that match and then do an overall loop.
loopchk = [x for x in self.AS_Alt if re.sub('[\|\s]','', x.lower()).strip() == re.sub('[\|\s]','', nspace_seriesname.lower()).strip()]
if len(loopchk) > 0 and loopchk[0] != '':
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[FILECHECKER] This should be an alternate: %s' % loopchk)
if any(['annual' in series_name.lower(), 'special' in series_name.lower()]):
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[FILECHECKER] Annual/Special detected - proceeding')
enable_annual = True
else:
loopchk = []
#logger.info('loopchk: ' + str(loopchk))
#if the names match up, and enable annuals isn't turned on - keep it all together.
if re.sub('\|', '', nspace_watchcomic.lower()).strip() == re.sub('\|', '', nspace_seriesname.lower()).strip() and enable_annual == False:
loopchk.append(nspace_watchcomic)
if any(['annual' in nspace_seriesname.lower(), 'special' in nspace_seriesname.lower()]):
if 'biannual' in nspace_seriesname.lower():
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[FILECHECKER] BiAnnual detected - wouldn\'t Deadpool be proud?')
nspace_seriesname = re.sub('biannual', '', nspace_seriesname).strip()
enable_annual = True
elif 'annual' in nspace_seriesname.lower():
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[FILECHECKER] Annual detected - proceeding cautiously.')
nspace_seriesname = re.sub('annual', '', nspace_seriesname).strip()
enable_annual = False
elif 'special' in nspace_seriesname.lower():
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[FILECHECKER] Special detected - proceeding cautiously.')
nspace_seriesname = re.sub('special', '', nspace_seriesname).strip()
enable_annual = False
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[FILECHECKER] Complete matching list of names to this file [%s] : %s' % (len(loopchk), loopchk))
for loopit in loopchk:
#now that we have the list of all possible matches for the watchcomic + alternate search names, we go through the list until we find a match.
modseries_name = loopit
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[FILECHECKER] AS_Tuple : %s' % self.AS_Tuple)
for ATS in self.AS_Tuple:
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[FILECHECKER] %s comparing to %s' % (ATS['AS_Alternate'], nspace_seriesname))
if re.sub('\|','', ATS['AS_Alternate'].lower()).strip() == re.sub('\|','', nspace_seriesname.lower()).strip():
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[FILECHECKER] Associating ComiciD : %s' % ATS['ComicID'])
annual_comicid = str(ATS['ComicID'])
modseries_name = ATS['AS_Alternate']
break
logger.fdebug('[FILECHECKER] %s - watchlist match on : %s' % (modseries_name, filename))
if enable_annual:
if annual_comicid is not None:
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('enable annual is on')
logger.fdebug('annual comicid is %s' % annual_comicid)
if 'biannual' in nspace_watchcomic.lower():
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('bi annual detected')
justthedigits = 'BiAnnual %s' % justthedigits
elif 'annual' in nspace_watchcomic.lower():
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('annual detected')
justthedigits = 'Annual %s' % justthedigits
elif 'special' in nspace_watchcomic.lower():
justthedigits = 'Special %s' % justthedigits
return {'process_status': 'match',
'sub': series_info['sub'],
'volume': series_info['series_volume'],
'match_type': None, #match_type - will eventually pass if it wasa folder vs. filename match,
'comicfilename': filename,
'comiclocation': series_info['comiclocation'],
'series_name': series_info['series_name'],
'series_volume': series_info['series_volume'],
'alt_series': series_info['alt_series'],
'alt_issue': series_info['alt_issue'],
'issue_year': series_info['issue_year'],
'issueid': series_info['issueid'],
'justthedigits': justthedigits,
'annual_comicid': annual_comicid,
'scangroup': series_info['scangroup'],
'booktype': series_info['booktype']}
else:
#logger.fdebug('[NO MATCH] ' + filename + ' [WATCHLIST:' + self.watchcomic + ']')
return {'process_status': 'fail',
'comicfilename': filename,
'sub': series_info['sub'],
'comiclocation': series_info['comiclocation'],
'series_name': series_info['series_name'],
'alt_series': series_info['alt_series'],
'alt_issue': series_info['alt_issue'],
'issue_number': series_info['issue_number'],
'series_volume': series_info['series_volume'],
'issue_year': series_info['issue_year'],
'issueid': series_info['issueid'],
'scangroup': series_info['scangroup'],
'booktype': series_info['booktype']}
def char_file_position(self, file, findchar, lastpos):
return file.find(findchar, lastpos)
def traverse_directories(self, dir):
filelist = []
comic_ext = ('.cbr','.cbz','.cb7','.pdf')
dir = dir.encode(mylar.SYS_ENCODING)
if all([mylar.CONFIG.ENABLE_TORRENTS is True, self.pp_mode is True]):
import db
myDB = db.DBConnection()
pp_crclist =[]
pp_crc = myDB.select("SELECT a.crc, b.IssueID FROM Snatched as a INNER JOIN issues as b ON a.IssueID=b.IssueID WHERE (a.Status='Post-Processed' or a.status='Snatched' or a.provider='32P' or a.provider='WWT' or a.provider='DEM') and a.crc is not NULL and (b.Status='Downloaded' or b.status='Archived') GROUP BY a.crc ORDER BY a.DateAdded")
for pp in pp_crc:
pp_crclist.append({'IssueID': pp['IssueID'],
'crc': pp['crc']})
for (dirname, subs, files) in os.walk(dir):
for fname in files:
if dirname == dir:
direc = None
else:
direc = dirname
if '.AppleDouble' in direc:
#Ignoring MAC OS Finder directory of cached files (/.AppleDouble/<name of file(s)>)
continue
if all([mylar.CONFIG.ENABLE_TORRENTS is True, self.pp_mode is True]):
tcrc = helpers.crc(os.path.join(dirname, fname).decode(mylar.SYS_ENCODING))
crcchk = [x for x in pp_crclist if tcrc == x['crc']]
if crcchk:
#logger.fdebug('[FILECHECKEER] Already post-processed this item %s - Ignoring' % fname)
continue
if os.path.splitext(fname)[1].lower().endswith(comic_ext):
if direc is None:
comicsize = os.path.getsize(os.path.join(dir, fname))
else:
comicsize = os.path.getsize(os.path.join(dir, direc, fname))
filelist.append({'directory': direc, #subdirectory if it exists
'filename': fname,
'comicsize': comicsize})
logger.info('there are %s files.' % len(filelist))
return filelist
def dynamic_replace(self, series_name):
mod_watchcomic = None
if self.watchcomic:
watchdynamic_handlers_match = [x for x in self.dynamic_handlers if x.lower() in self.watchcomic.lower()]
#logger.fdebug('watch dynamic handlers recognized : ' + str(watchdynamic_handlers_match))
watchdynamic_replacements_match = [x for x in self.dynamic_replacements if x.lower() in self.watchcomic.lower()]
#logger.fdebug('watch dynamic replacements recognized : ' + str(watchdynamic_replacements_match))
mod_watchcomic = re.sub('[\s\s+\_\.]', '%$', self.watchcomic)
mod_watchcomic = re.sub('[\#]', '', mod_watchcomic)
mod_find = []
wdrm_find = []
if any([watchdynamic_handlers_match, watchdynamic_replacements_match]):
for wdhm in watchdynamic_handlers_match:
#check the watchcomic
#first get the position.
mod_find.extend([m.start() for m in re.finditer('\\' + wdhm, mod_watchcomic)])
if len(mod_find) > 0:
for mf in mod_find:
spacer = ''
for i in range(0, len(wdhm)):
spacer+='|'
mod_watchcomic = mod_watchcomic[:mf] + spacer + mod_watchcomic[mf+1:]
for wdrm in watchdynamic_replacements_match:
wdrm_find.extend([m.start() for m in re.finditer(wdrm.lower(), mod_watchcomic.lower())])
if len(wdrm_find) > 0:
for wd in wdrm_find:
spacer = ''
for i in range(0, len(wdrm)):
spacer+='|'
mod_watchcomic = mod_watchcomic[:wd] + spacer + mod_watchcomic[wd+len(wdrm):]
series_name = re.sub(u'\u2014', ' - ', series_name)
series_name = re.sub(u'\u2013', ' - ', series_name)
seriesdynamic_handlers_match = [x for x in self.dynamic_handlers if x.lower() in series_name.lower()]
#logger.fdebug('series dynamic handlers recognized : ' + str(seriesdynamic_handlers_match))
seriesdynamic_replacements_match = [x for x in self.dynamic_replacements if x.lower() in series_name.lower()]
#logger.fdebug('series dynamic replacements recognized : ' + str(seriesdynamic_replacements_match))
mod_seriesname = re.sub('[\s\s+\_\.]', '%$', series_name)
mod_seriesname = re.sub('[\#]', '', mod_seriesname)
ser_find = []
sdrm_find = []
if any([seriesdynamic_handlers_match, seriesdynamic_replacements_match]):
for sdhm in seriesdynamic_handlers_match:
#check the series_name
ser_find.extend([m.start() for m in re.finditer('\\' + sdhm, mod_seriesname)])
if len(ser_find) > 0:
for sf in ser_find:
spacer = ''
for i in range(0, len(sdhm)):
spacer+='|'
mod_seriesname = mod_seriesname[:sf] + spacer + mod_seriesname[sf+1:]
for sdrm in seriesdynamic_replacements_match:
sdrm_find.extend([m.start() for m in re.finditer(sdrm.lower(), mod_seriesname.lower())])
if len(sdrm_find) > 0:
for sd in sdrm_find:
spacer = ''
for i in range(0, len(sdrm)):
spacer+='|'
mod_seriesname = mod_seriesname[:sd] + spacer + mod_seriesname[sd+len(sdrm):]
if mod_watchcomic:
mod_watchcomic = re.sub('\|+', '|', mod_watchcomic)
if mod_watchcomic.endswith('|'):
mod_watchcomic = mod_watchcomic[:-1]
mod_watchcomic = re.sub('[\%\$]+', '', mod_watchcomic)
mod_seriesname = re.sub('\|+', '|', mod_seriesname)
if mod_seriesname.endswith('|'):
mod_seriesname = mod_seriesname[:-1]
mod_seriesname = re.sub('[\%\$]+', '', mod_seriesname)
return {'mod_watchcomic': mod_watchcomic,
'mod_seriesname': mod_seriesname}
def altcheck(self):
#iniitate the alternate list here so we can add in the different alternate search names (if present)
AS_Alt = []
AS_Tuple = []
if self.AlternateSearch is not None and self.AlternateSearch != 'None':
chkthealt = self.AlternateSearch.split('##')
#logger.info('[' + str(len(chkthealt)) + '] chkthealt: ' + str(chkthealt))
i = 0
while (i <= len(chkthealt)):
try:
calt = chkthealt[i]
except IndexError:
break
AS_tupled = False
AS_Alternate = re.sub('##', '', calt)
if '!!' in AS_Alternate:
# if it's !! present, it's the comicid associated with the series as an added annual.
# extract the !!, store it and then remove it so things will continue.
as_start = AS_Alternate.find('!!')
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('as_start: %s --- %s' % (as_start, AS_Alternate[as_start:]))
as_end = AS_Alternate.find('##', as_start)
if as_end == -1:
as_end = len(AS_Alternate)
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('as_start: %s --- %s' % (as_end, AS_Alternate[as_start:as_end]))
AS_ComicID = AS_Alternate[as_start +2:as_end]
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('[FILECHECKER] Extracted comicid for given annual : %s' % AS_ComicID)
AS_Alternate = re.sub('!!' + str(AS_ComicID), '', AS_Alternate)
AS_tupled = True
as_dyninfo = self.dynamic_replace(AS_Alternate)
altsearchcomic = as_dyninfo['mod_seriesname']
if AS_tupled:
AS_Tuple.append({"ComicID": AS_ComicID,
"AS_Alternate": altsearchcomic})
AS_Alt.append(altsearchcomic)
i+=1
else:
#create random characters so it will never match.
altsearchcomic = "127372873872871091383 abdkhjhskjhkjdhakajhf"
AS_Alt.append(altsearchcomic)
return {'AS_Alt': AS_Alt,
'AS_Tuple': AS_Tuple}
def checkthedate(self, txt, fulldate=False, cnt=0):
# txt='''\
# Jan 19, 1990
# January 19, 1990
# Jan 19,1990
# 01/19/1990
# 01/19/90
# 1990
# Jan 1990
# January1990'''
fmts = ('%Y','%b %d, %Y','%B %d, %Y','%B %d %Y','%m/%d/%Y','%m/%d/%y','(%m/%d/%Y)','%b %Y','%B%Y','%b %d,%Y','%m-%Y','%B %Y','%Y-%m-%d','%Y-%m','%Y%m')
mnths = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
parsed=[]
if fulldate is False:
for e in txt.splitlines():
for fmt in fmts:
try:
t = dt.datetime.strptime(e, fmt)
parsed.append((e, fmt, t))
break
except ValueError as err:
pass
else:
for e in txt.split():
if cnt == 0:
for x in mnths:
mnth = re.sub('\.', '', e.lower())
if x.lower() in mnth and len(mnth) <= 4:
add_date = x + ' '
cnt+=1
break
elif cnt == 1:
issnumb = re.sub(',', '', e).strip()
if issnumb.isdigit() and int(issnumb) < 31:
add_date += issnumb + ', '
cnt+=1
elif cnt == 2:
possyear = helpers.cleanhtml(re.sub('\.', '', e).strip())
if possyear.isdigit() and int(possyear) > 1970 and int(possyear) < 2020:
add_date += possyear
cnt +=1
if cnt == 3:
return self.checkthedate(add_date, fulldate=False, cnt=-1)
if cnt <= 0:
for fmt in fmts:
try:
t = dt.datetime.strptime(e, fmt)
parsed.append((e, fmt, t))
break
except ValueError as err:
pass
# check that all the cases are handled
success={t[0] for t in parsed}
for e in txt.splitlines():
if e not in success:
pass #print e
dateline = None
#logger.info('parsed: %s' % parsed)
for t in parsed:
#logger.fdebug('"{:20}" => "{:20}" => {}'.format(*t))
if fulldate is False and cnt != -1:
dateline = t[2].year
else:
dateline = t[2].strftime('%Y-%m-%d')
break
return dateline
def validateAndCreateDirectory(dir, create=False, module=None, dmode=None):
if module is None:
module = ''
module += '[DIRECTORY-CHECK]'
if dmode is None:
dirmode = 'comic'
else:
dirmode = dmode
try:
if os.path.exists(dir):
logger.info('%s Found %s directory: %s' % (module, dirmode, dir))
return True
else:
logger.warn('%s Could not find %s directory: %s' % (module, dirmode, dir))
if create:
if dir.strip():
logger.info('%s Creating %s directory (%s) : %s' % (module, dirmode, mylar.CONFIG.CHMOD_DIR, dir))
try:
os.umask(0) # this is probably redudant, but it doesn't hurt to clear the umask here.
if mylar.CONFIG.ENFORCE_PERMS:
permission = int(mylar.CONFIG.CHMOD_DIR, 8)
os.makedirs(dir.rstrip(), permission)
setperms(dir.rstrip(), True)
else:
os.makedirs(dir.rstrip())
except OSError as e:
logger.warn('%s Could not create directory: %s [%s]. Aborting' % (module, dir, e))
return False
else:
return True
else:
logger.warn('%s Provided directory [%s] is blank. Aborting.' % (module, dir))
return False
except OSError as e:
logger.warn('%s Could not create directory: %s [%s]. Aborting.' % (module, dir, e))
return False
return False
def setperms(path, dir=False):
if 'windows' not in mylar.OS_DETECT.lower():
try:
os.umask(0) # this is probably redudant, but it doesn't hurt to clear the umask here.
if mylar.CONFIG.CHGROUP:
if mylar.CONFIG.CHOWNER is None or mylar.CONFIG.CHOWNER == 'None' or mylar.CONFIG.CHOWNER == '':
import getpass
mylar.CONFIG.CHOWNER = getpass.getuser()
if not mylar.CONFIG.CHOWNER.isdigit():
from pwd import getpwnam
chowner = getpwnam(mylar.CONFIG.CHOWNER)[2]
else:
chowner = int(mylar.CONFIG.CHOWNER)
if not mylar.CONFIG.CHGROUP.isdigit():
from grp import getgrnam
chgroup = getgrnam(mylar.CONFIG.CHGROUP)[2]
else:
chgroup = int(mylar.CONFIG.CHGROUP)
if dir:
permission = int(mylar.CONFIG.CHMOD_DIR, 8)
os.chmod(path, permission)
os.chown(path, chowner, chgroup)
elif os.path.isfile(path):
permission = int(mylar.CONFIG.CHMOD_FILE, 8)
os.chown(path, chowner, chgroup)
os.chmod(path, permission)
else:
for root, dirs, files in os.walk(path):
for momo in dirs:
permission = int(mylar.CONFIG.CHMOD_DIR, 8)
os.chown(os.path.join(root, momo), chowner, chgroup)
os.chmod(os.path.join(root, momo), permission)
for momo in files:
permission = int(mylar.CONFIG.CHMOD_FILE, 8)
os.chown(os.path.join(root, momo), chowner, chgroup)
os.chmod(os.path.join(root, momo), permission)
logger.fdebug('Successfully changed ownership and permissions [' + str(mylar.CONFIG.CHOWNER) + ':' + str(mylar.CONFIG.CHGROUP) + '] / [' + str(mylar.CONFIG.CHMOD_DIR) + ' / ' + str(mylar.CONFIG.CHMOD_FILE) + ']')
elif os.path.isfile(path):
permission = int(mylar.CONFIG.CHMOD_FILE, 8)
os.chmod(path, permission)
else:
for root, dirs, files in os.walk(path):
for momo in dirs:
permission = int(mylar.CONFIG.CHMOD_DIR, 8)
os.chmod(os.path.join(root, momo), permission)
for momo in files:
permission = int(mylar.CONFIG.CHMOD_FILE, 8)
os.chmod(os.path.join(root, momo), permission)
logger.fdebug('Successfully changed permissions [' + str(mylar.CONFIG.CHMOD_DIR) + ' / ' + str(mylar.CONFIG.CHMOD_FILE) + ']')
except OSError:
logger.error('Could not change permissions : %s. Exiting...' % path)
return
#if __name__ == '__main__':
# test = FileChecker()
# test.getlist()
| 103,577 | Python | .py | 1,617 | 41.577613 | 395 | 0.468448 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,264 | findcomicfeed.py | evilhero_mylar/mylar/findcomicfeed.py | #!/usr/bin/env python
import os
import sys
import time
import feedparser
import re
import logger
import mylar
import unicodedata
import urllib
def Startit(searchName, searchIssue, searchYear, ComicVersion, IssDateFix, booktype=None):
cName = searchName
#clean up searchName due to webparse/redudant naming that would return too specific of results.
commons = ['and', 'the', '&', '-']
for x in commons:
cnt = 0
for m in re.finditer(x, searchName.lower()):
cnt +=1
tehstart = m.start()
tehend = m.end()
if any([x == 'the', x == 'and']):
if len(searchName) == tehend:
tehend =-1
if all([tehstart == 0, searchName[tehend] == ' ']) or all([tehstart != 0, searchName[tehstart-1] == ' ', searchName[tehend] == ' ']):
searchName = searchName.replace(x, ' ', cnt)
else:
continue
else:
searchName = searchName.replace(x, ' ', cnt)
searchName = re.sub('\s+', ' ', searchName)
searchName = re.sub("[\,\:]", "", searchName).strip()
#logger.fdebug("searchname: %s" % searchName)
#logger.fdebug("issue: %s" % searchIssue)
#logger.fdebug("year: %s" % searchYear)
encodeSearch = urllib.quote_plus(searchName)
splitSearch = encodeSearch.split(" ")
tmpsearchIssue = searchIssue
if any([booktype == 'One-Shot', booktype == 'TPB']):
tmpsearchIssue = '1'
loop = 4
elif len(searchIssue) == 1:
loop = 3
elif len(searchIssue) == 2:
loop = 2
else:
loop = 1
if "-" in searchName:
searchName = searchName.replace("-", '((\\s)?[-:])?(\\s)?')
regexName = searchName.replace(" ", '((\\s)?[-:])?(\\s)?')
if mylar.CONFIG.USE_MINSIZE is True:
minsize = str(mylar.CONFIG.MINSIZE)
else:
minsize = '10'
size_constraints = "&minsize=" + minsize
if mylar.CONFIG.USE_MAXSIZE is True:
maxsize = str(mylar.CONFIG.MAXSIZE)
else:
maxsize = '0'
size_constraints += "&maxsize=" + maxsize
if mylar.CONFIG.USENET_RETENTION is not None:
max_age = "&maxage=" + str(mylar.CONFIG.USENET_RETENTION)
else:
max_age = "&maxage=0"
feeds = []
i = 1
while (i <= loop):
if i == 1:
searchmethod = tmpsearchIssue
elif i == 2:
searchmethod = '0' + tmpsearchIssue
elif i == 3:
searchmethod = '00' + tmpsearchIssue
elif i == 4:
searchmethod = tmpsearchIssue
else:
break
if i == 4:
logger.fdebug('Now searching experimental for %s to try and ensure all the bases are covered' % cName)
joinSearch = "+".join(splitSearch)
else:
logger.fdebug('Now searching experimental for issue number: %s to try and ensure all the bases are covered' % searchmethod)
joinSearch = "+".join(splitSearch) + "+" +searchmethod
if mylar.CONFIG.PREFERRED_QUALITY == 1: joinSearch = joinSearch + " .cbr"
elif mylar.CONFIG.PREFERRED_QUALITY == 2: joinSearch = joinSearch + " .cbz"
feeds.append(feedparser.parse(mylar.EXPURL + "search/rss?q=%s&max=50&minage=0%s&hidespam=1&hidepassword=1&sort=agedesc%s&complete=0&hidecross=0&hasNFO=0&poster=&g[]=85" % (joinSearch, max_age, size_constraints)))
time.sleep(5)
if mylar.CONFIG.ALTEXPERIMENTAL:
feeds.append(feedparser.parse(mylar.EXPURL + "search/rss?q=%s&max=50&minage=0%s&hidespam=1&hidepassword=1&sort=agedesc%s&complete=0&hidecross=0&hasNFO=0&poster=&g[]=86" % (joinSearch, max_age, size_constraints)))
time.sleep(5)
i+=1
entries = []
mres = {}
tallycount = 0
for feed in feeds:
totNum = len(feed.entries)
tallycount += len(feed.entries)
#keyPair = {}
keyPair = []
regList = []
countUp = 0
while countUp < totNum:
urlParse = feed.entries[countUp].enclosures[0]
#keyPair[feed.entries[countUp].title] = feed.entries[countUp].link
#keyPair[feed.entries[countUp].title] = urlParse["href"]
keyPair.append({"title": feed.entries[countUp].title,
"link": urlParse["href"],
"length": urlParse["length"],
"pubdate": feed.entries[countUp].updated})
countUp=countUp +1
# thanks to SpammyHagar for spending the time in compiling these regEx's!
regExTest=""
regEx = "(%s\\s*(0)?(0)?%s\\s*\\(%s\\))" %(regexName, searchIssue, searchYear)
regExOne = "(%s\\s*(0)?(0)?%s\\s*\\(.*?\\)\\s*\\(%s\\))" %(regexName, searchIssue, searchYear)
#Sometimes comics aren't actually published the same year comicVine says - trying to adjust for these cases
regExTwo = "(%s\\s*(0)?(0)?%s\\s*\\(%s\\))" %(regexName, searchIssue, int(searchYear) +1)
regExThree = "(%s\\s*(0)?(0)?%s\\s*\\(%s\\))" %(regexName, searchIssue, int(searchYear) -1)
regExFour = "(%s\\s*(0)?(0)?%s\\s*\\(.*?\\)\\s*\\(%s\\))" %(regexName, searchIssue, int(searchYear) +1)
regExFive = "(%s\\s*(0)?(0)?%s\\s*\\(.*?\\)\\s*\\(%s\\))" %(regexName, searchIssue, int(searchYear) -1)
regexList=[regEx, regExOne, regExTwo, regExThree, regExFour, regExFive]
except_list=['releases', 'gold line', 'distribution', '0-day', '0 day', '0day', 'o-day']
for entry in keyPair:
title = entry['title']
#logger.fdebug("titlesplit: " + str(title.split("\"")))
splitTitle = title.split("\"")
noYear = 'False'
_digits = re.compile('\d')
for subs in splitTitle:
#logger.fdebug('sub:' + subs)
regExCount = 0
if len(subs) >= len(cName) and not any(d in subs.lower() for d in except_list) and bool(_digits.search(subs)) is True:
#Looping through dictionary to run each regEx - length + regex is determined by regexList up top.
# while regExCount < len(regexList):
# regExTest = re.findall(regexList[regExCount], subs, flags=re.IGNORECASE)
# regExCount = regExCount +1
# if regExTest:
# logger.fdebug(title)
# entries.append({
# 'title': subs,
# 'link': str(link)
# })
# this will still match on crap like 'For SomeSomayes' especially if the series length < 'For SomeSomayes'
if subs.lower().startswith('for'):
if cName.lower().startswith('for'):
pass
else:
#this is the crap we ignore. Continue (commented else, as it spams the logs)
#logger.fdebug('this starts with FOR : ' + str(subs) + '. This is not present in the series - ignoring.')
continue
#logger.fdebug('match.')
if IssDateFix != "no":
if IssDateFix == "01" or IssDateFix == "02": ComicYearFix = str(int(searchYear) - 1)
else: ComicYearFix = str(int(searchYear) + 1)
else:
ComicYearFix = searchYear
if searchYear not in subs and ComicYearFix not in subs:
noYear = 'True'
noYearline = subs
if (searchYear in subs or ComicYearFix in subs) and noYear == 'True':
#this would occur on the next check in the line, if year exists and
#the noYear check in the first check came back valid append it
subs = noYearline + ' (' + searchYear + ')'
noYear = 'False'
if noYear == 'False':
entries.append({
'title': subs,
'link': entry['link'],
'pubdate': entry['pubdate'],
'length': entry['length']
})
break # break out so we don't write more shit.
# if len(entries) >= 1:
if tallycount >= 1:
mres['entries'] = entries
return mres
else:
logger.fdebug("No Results Found")
return "no results"
| 8,669 | Python | .py | 177 | 37.19774 | 224 | 0.531032 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,265 | auth32p.py | evilhero_mylar/mylar/auth32p.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import urllib2
import json
import re
import time
import math
import datetime
import os
import requests
from bs4 import BeautifulSoup
from cookielib import LWPCookieJar
import cfscrape
from operator import itemgetter
import mylar
from mylar import db, logger, filechecker, helpers
class info32p(object):
def __init__(self, reauthenticate=False, searchterm=None, test=False):
self.module = '[32P-AUTHENTICATION]'
self.url = 'https://32pag.es/user.php?action=notify'
self.headers = {'Content-type': 'application/x-www-form-urlencoded',
'Accept-Charset': 'utf-8',
'User-Agent': 'Mozilla/5.0'}
if test:
self.username_32p = test['username']
self.password_32p = test['password']
self.test = True
else:
self.username_32p = mylar.CONFIG.USERNAME_32P
self.password_32p = mylar.CONFIG.PASSWORD_32P
self.test = False
self.error = None
self.method = None
if any([mylar.CONFIG.MODE_32P is True, self.test is True]):
lses = self.LoginSession(self.username_32p, self.password_32p)
if not lses.login():
if not self.test:
logger.error('%s [LOGIN FAILED] Disabling 32P provider until login error(s) can be fixed in order to avoid temporary bans.' % self.module)
return "disable"
else:
if self.error:
return self.error #rtnmsg
else:
return self.method
else:
logger.fdebug('%s [LOGIN SUCCESS] Now preparing for the use of 32P keyed authentication...' % self.module)
self.authkey = lses.authkey
self.passkey = lses.passkey
self.session = lses.ses
self.uid = lses.uid
try:
mylar.INKDROPS_32P = int(math.floor(float(lses.inkdrops['results'][0]['inkdrops'])))
except:
mylar.INKDROPS_32P = lses.inkdrops['results'][0]['inkdrops']
else:
self.session = requests.Session()
self.reauthenticate = reauthenticate
self.searchterm = searchterm
self.publisher_list = {'Entertainment', 'Press', 'Comics', 'Publishing', 'Comix', 'Studios!'}
def authenticate(self):
if self.test:
return {'status': True, 'inkdrops': mylar.INKDROPS_32P}
feedinfo = []
try:
# with cfscrape.create_scraper(delay=15) as s:
# s.headers = self.headers
# cj = LWPCookieJar(os.path.join(mylar.CONFIG.SECURE_DIR, ".32p_cookies.dat"))
# cj.load()
# s.cookies = cj
if mylar.CONFIG.VERIFY_32P == 1 or mylar.CONFIG.VERIFY_32P == True:
verify = True
else:
verify = False
# logger.fdebug('[32P] Verify SSL set to : %s' % verify)
if not verify:
# #32P throws back an insecure warning because it can't validate against the CA. The below suppresses the message just for 32P instead of being displa$
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# post to the login form
r = self.session.post(self.url, verify=verify, allow_redirects=True)
#logger.debug(self.module + " Content session reply" + r.text)
#need a way to find response code (200=OK), but returns 200 for everything even failed signons (returns a blank page)
#logger.info('[32P] response: ' + str(r.content))
soup = BeautifulSoup(r.content, "html.parser")
soup.prettify()
if self.searchterm:
logger.info('[32P] Successfully authenticated. Initiating search for : %s' % self.searchterm)
return self.search32p(s)
logger.info('[32P] Successfully authenticated.')
all_script = soup.find_all("script", {"src": False})
all_script2 = soup.find_all("link", {"rel": "alternate"})
authfound = False
logger.info('%s Attempting to integrate with all of your 32P Notification feeds.' % self.module)
#get inkdrop count ...
#user_info = soup.find_all(attrs={"class": "stat"})
#inkdrops = user_info[0]['title']
#logger.info('INKDROPS: ' + str(inkdrops))
for al in all_script2:
alurl = al['href']
if 'auth=' in alurl and 'torrents_notify' in alurl and not authfound:
f1 = alurl.find('auth=')
f2 = alurl.find('&', f1 + 1)
auth = alurl[f1 +5:f2]
authfound = True
#logger.fdebug(self.module + ' Auth:' + str(auth))
#p1 = alurl.find('passkey=')
#p2 = alurl.find('&', p1 + 1)
#passkey = alurl[p1 +8:p2]
#logger.fdebug(self.module + ' Passkey:' + str(passkey))
if self.reauthenticate: break
if 'torrents_notify' in alurl and ('torrents_notify_' + str(self.passkey)) not in alurl:
notifyname_st = alurl.find('name=')
notifyname_en = alurl.find('&', notifyname_st +1)
if notifyname_en == -1: notifyname_en = len(alurl)
notifyname = alurl[notifyname_st +5:notifyname_en]
notifynumber_st = alurl.find('torrents_notify_')
notifynumber_en = alurl.find('_', notifynumber_st +17)
notifynumber = alurl[notifynumber_st:notifynumber_en]
logger.fdebug('%s [NOTIFICATION: %s] Notification ID: %s' % (self.module, notifyname,notifynumber))
#generate the rss-url here
feedinfo.append({'feed': notifynumber + '_' + str(self.passkey),
'feedname': notifyname,
'user': str(self.uid),
'auth': auth,
'passkey': str(self.passkey),
'authkey': str(self.authkey)})
except (requests.exceptions.Timeout, EnvironmentError):
logger.warn('Unable to retrieve information from 32Pages - either it is not responding/is down or something else is happening that is stopping me.')
return
#set the keys here that will be used to download.
try:
mylar.CONFIG.PASSKEY_32P = str(self.passkey)
mylar.AUTHKEY_32P = str(self.authkey) # probably not needed here.
mylar.KEYS_32P = {}
mylar.KEYS_32P = {"user": str(self.uid),
"auth": auth,
"passkey": str(self.passkey),
"authkey": str(self.authkey)}
except NameError:
logger.warn('Unable to retrieve information from 32Pages - either it is not responding/is down or something else is happening that is stopping me.')
return
if self.reauthenticate:
return
else:
mylar.FEEDINFO_32P = feedinfo
return feedinfo
def searchit(self):
chk_id = None
#logger.info('searchterm: %s' % self.searchterm)
#self.searchterm is a tuple containing series name, issue number, volume and publisher.
series_search = self.searchterm['series']
issue_search = self.searchterm['issue']
volume_search = self.searchterm['volume']
if series_search.startswith('0-Day Comics Pack'):
#issue = '21' = WED, #volume='2' = 2nd month
torrentid = 22247 #2018
publisher_search = None #'2' #2nd month
comic_id = None
elif all([self.searchterm['torrentid_32p'] is not None, self.searchterm['torrentid_32p'] != 'None']):
torrentid = self.searchterm['torrentid_32p']
comic_id = self.searchterm['id']
publisher_search = self.searchterm['publisher']
else:
torrentid = None
comic_id = self.searchterm['id']
annualize = False
if 'annual' in series_search.lower():
series_search = re.sub(' annual', '', series_search.lower()).strip()
annualize = True
publisher_search = self.searchterm['publisher']
spl = [x for x in self.publisher_list if x in publisher_search]
for x in spl:
publisher_search = re.sub(x, '', publisher_search).strip()
#logger.info('publisher search set to : %s' % publisher_search)
# lookup the ComicID in the 32p sqlite3 table to pull the series_id to use.
if comic_id:
chk_id = helpers.checkthe_id(comic_id)
if any([chk_id is None, mylar.CONFIG.DEEP_SEARCH_32P is True]):
#generate the dynamic name of the series here so we can match it up
as_d = filechecker.FileChecker()
as_dinfo = as_d.dynamic_replace(series_search)
mod_series = re.sub('\|','', as_dinfo['mod_seriesname']).strip()
as_puinfo = as_d.dynamic_replace(publisher_search)
pub_series = as_puinfo['mod_seriesname']
logger.fdebug('series_search: %s' % series_search)
if '/' in series_search:
series_search = series_search[:series_search.find('/')]
if ':' in series_search:
series_search = series_search[:series_search.find(':')]
if ',' in series_search:
series_search = series_search[:series_search.find(',')]
logger.fdebug('config.search_32p: %s' % mylar.CONFIG.SEARCH_32P)
if mylar.CONFIG.SEARCH_32P is False:
url = 'https://walksoftly.itsaninja.party/serieslist.php'
params = {'series': re.sub('\|','', mod_series.lower()).strip()} #series_search}
logger.fdebug('search query: %s' % re.sub('\|', '', mod_series.lower()).strip())
try:
t = requests.get(url, params=params, verify=True, headers={'USER-AGENT': mylar.USER_AGENT[:mylar.USER_AGENT.find('/')+7] + mylar.USER_AGENT[mylar.USER_AGENT.find('(')+1]})
except requests.exceptions.RequestException as e:
logger.warn(e)
return "no results"
if t.status_code == '619':
logger.warn('[%s] Unable to retrieve data from site.' % t.status_code)
return "no results"
elif t.status_code == '999':
logger.warn('[%s] No series title was provided to the search query.' % t.status_code)
return "no results"
try:
results = t.json()
except:
results = t.text
if len(results) == 0:
logger.warn('No results found for search on 32P.')
return "no results"
# with cfscrape.create_scraper(delay=15) as s:
# s.headers = self.headers
# cj = LWPCookieJar(os.path.join(mylar.CONFIG.SECURE_DIR, ".32p_cookies.dat"))
# cj.load()
# s.cookies = cj
data = []
pdata = []
pubmatch = False
if any([series_search.startswith('0-Day Comics Pack'), torrentid is not None]):
data.append({"id": torrentid,
"series": series_search})
else:
if any([not chk_id, mylar.CONFIG.DEEP_SEARCH_32P is True]):
if mylar.CONFIG.SEARCH_32P is True:
url = 'https://32pag.es/torrents.php' #?action=serieslist&filter=' + series_search #&filter=F
params = {'action': 'serieslist', 'filter': series_search}
time.sleep(1) #just to make sure we don't hammer, 1s pause.
t = self.session.get(url, params=params, verify=True, allow_redirects=True)
soup = BeautifulSoup(t.content, "html.parser")
results = soup.find_all("a", {"class":"object-qtip"},{"data-type":"torrentgroup"})
for r in results:
if mylar.CONFIG.SEARCH_32P is True:
torrentid = r['data-id']
torrentname = r.findNext(text=True)
torrentname = torrentname.strip()
else:
torrentid = r['id']
torrentname = r['series']
as_d = filechecker.FileChecker()
as_dinfo = as_d.dynamic_replace(torrentname)
seriesresult = re.sub('\|','', as_dinfo['mod_seriesname']).strip()
logger.fdebug('searchresult: %s --- %s [%s]' % (seriesresult, mod_series, publisher_search))
if seriesresult.lower() == mod_series.lower():
logger.fdebug('[MATCH] %s [%s]' % (torrentname, torrentid))
data.append({"id": torrentid,
"series": torrentname})
elif publisher_search.lower() in seriesresult.lower():
logger.fdebug('[MATCH] Publisher match.')
tmp_torrentname = re.sub(publisher_search.lower(), '', seriesresult.lower()).strip()
as_t = filechecker.FileChecker()
as_tinfo = as_t.dynamic_replace(tmp_torrentname)
if re.sub('\|', '', as_tinfo['mod_seriesname']).strip() == mod_series.lower():
logger.fdebug('[MATCH] %s [%s]' % (torrentname, torrentid))
pdata.append({"id": torrentid,
"series": torrentname})
pubmatch = True
logger.fdebug('%s series listed for searching that match.' % len(data))
else:
logger.fdebug('Exact series ID already discovered previously. Setting to : %s [%s]' % (chk_id['series'], chk_id['id']))
pdata.append({"id": chk_id['id'],
"series": chk_id['series']})
pubmatch = True
if all([len(data) == 0, len(pdata) == 0]):
return "no results"
else:
dataset = []
if len(data) > 0:
dataset += data
if len(pdata) > 0:
dataset += pdata
logger.fdebug(str(len(dataset)) + ' series match the tile being searched for on 32P...')
if all([chk_id is None, not series_search.startswith('0-Day Comics Pack'), self.searchterm['torrentid_32p'] is not None, self.searchterm['torrentid_32p'] != 'None']) and any([len(data) == 1, len(pdata) == 1]):
#update the 32p_reference so we avoid doing a url lookup next time
helpers.checkthe_id(comic_id, dataset)
else:
if all([not series_search.startswith('0-Day Comics Pack'), self.searchterm['torrentid_32p'] is not None, self.searchterm['torrentid_32p'] != 'None']):
pass
else:
logger.debug('Unable to properly verify reference on 32P - will update the 32P reference point once the issue has been successfully matched against.')
results32p = []
resultlist = {}
for x in dataset:
#for 0-day packs, issue=week#, volume=month, id=0-day year pack (ie.issue=21&volume=2 for feb.21st)
payload = {"action": "groupsearch",
"id": x['id'], #searchid,
"issue": issue_search}
#in order to match up against 0-day stuff, volume has to be none at this point
#when doing other searches tho, this should be allowed to go through
#if all([volume_search != 'None', volume_search is not None]):
# payload.update({'volume': re.sub('v', '', volume_search).strip()})
if series_search.startswith('0-Day Comics Pack'):
payload.update({"volume": volume_search})
payload = json.dumps(payload)
payload = json.loads(payload)
logger.fdebug('payload: %s' % payload)
url = 'https://32pag.es/ajax.php'
time.sleep(1) #just to make sure we don't hammer, 1s pause.
try:
d = self.session.get(url, params=payload, verify=True, allow_redirects=True)
except Exception as e:
logger.error('%s [%s] Could not POST URL %s' % (self.module, e, url))
try:
searchResults = d.json()
except Exception as e:
searchResults = d.text
logger.debug('[%s] %s Search Result did not return valid JSON, falling back on text: %s' % (e, self.module, searchResults.text))
return False
if searchResults['status'] == 'success' and searchResults['count'] > 0:
logger.fdebug('successfully retrieved %s search results' % searchResults['count'])
for a in searchResults['details']:
if series_search.startswith('0-Day Comics Pack'):
title = series_search
else:
title = self.searchterm['series'] + ' v' + a['volume'] + ' #' + a['issues']
results32p.append({'link': a['id'],
'title': title,
'filesize': a['size'],
'issues': a['issues'],
'pack': a['pack'],
'format': a['format'],
'language': a['language'],
'seeders': a['seeders'],
'leechers': a['leechers'],
'scanner': a['scanner'],
'chkit': {'id': x['id'], 'series': x['series']},
'pubdate': datetime.datetime.fromtimestamp(float(a['upload_time'])).strftime('%a, %d %b %Y %H:%M:%S'),
'int_pubdate': float(a['upload_time'])})
else:
logger.fdebug('32P did not return any valid search results.')
if len(results32p) > 0:
resultlist['entries'] = sorted(results32p, key=itemgetter('pack','title'), reverse=False)
logger.debug('%s Resultslist: %s' % (self.module, resultlist))
else:
resultlist = 'no results'
return resultlist
def downloadfile(self, payload, filepath):
url = 'https://32pag.es/torrents.php'
try:
r = self.session.get(url, params=payload, verify=True, stream=True, allow_redirects=True)
except Exception as e:
logger.error('%s [%s] Could not POST URL %s' % ('[32P-DOWNLOADER]', e, url))
return False
if str(r.status_code) != '200':
logger.warn('Unable to download torrent from 32P [Status Code returned: %s]' % r.status_code)
if str(r.status_code) == '404':
logger.warn('[32P-CACHED_ENTRY] Entry found in 32P cache - incorrect. Torrent has probably been merged into a pack, or another series id. Removing from cache.')
self.delete_cache_entry(payload['id'])
else:
logger.fdebug('content: %s' % r.content)
return False
with open(filepath, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
return True
def delete_cache_entry(self, id):
myDB = db.DBConnection()
myDB.action("DELETE FROM rssdb WHERE link=? AND Site='32P'", [id])
class LoginSession(object):
def __init__(self, un, pw, session_path=None):
'''
Params:
un: account username (required)
pw: account password (required)
session_path: the path to the actual file you want to persist your cookies in
If blank, saves to $HOME/.32p_cookies.dat
'''
self.module = '[32P-AUTHENTICATION]'
try:
self.ses = cfscrape.create_scraper(delay=15)
except Exception as e:
logger.error('%s Can\'t create session with cfscrape' % self.module)
self.session_path = session_path if session_path is not None else os.path.join(mylar.CONFIG.SECURE_DIR, ".32p_cookies.dat")
self.ses.cookies = LWPCookieJar(self.session_path)
if not os.path.exists(self.session_path):
logger.fdebug('%s Session cookie does not exist. Signing in and Creating.' % self.module)
self.ses.cookies.save()
else:
logger.fdebug('%s Session cookie found. Attempting to load...' % self.module)
self.ses.cookies.load(ignore_discard=True)
self.un = un
self.pw = pw
self.authkey = None
self.passkey = None
self.uid = None
self.inkdrops = None
def cookie_exists(self, name):
'''
Checks if cookie <name> exists in self.ses.cookies
Beware - this doesn't match domain, so only use this method on one domain
'''
for ci in self.ses.cookies:
if (ci.name == name):
return True
return False
def cookie_value(self, name, default=None):
'''
Returns the value of the cookie name, returning default if it doesn't exist.
Beware - this doesn't match domain too, so only use this method on one domain
'''
for ci in self.ses.cookies:
if (ci.name == name):
return ci.value
return default
def valid_skey_attempt(self, skey):
'''
Not generally the proper method to call - call test_key_valid()
instead - which calls this method.
Attempts to fetch data via an ajax method that will fail if not
authorized. The parameter skey should be set to the string
value of the cookie named session.
Returns: True on success, False on failure. Side Effects: Sets
self.uid, self,authkey and self.passkey
'''
u = '''https://32pag.es/ajax.php'''
params = {'action': 'index'}
testcookie = dict(session=skey)
try:
r = self.ses.get(u, params=params, timeout=60, allow_redirects=False, cookies=testcookie)
except Exception as e:
logger.error('Got an exception [%s] trying to GET to: %s' % (e,u))
self.error = {'status':'error', 'message':'exception trying to retrieve site'}
return False
if r.status_code != 200:
if r.status_code == 302:
newloc = r.headers.get('Location', '')
logger.warn('Got redirect from the POST-ajax action=login GET: %s' % newloc)
self.error = {'status':'redirect-error', 'message':'got redirect from POST-ajax login action : ' + newloc}
else:
logger.error('Got bad status code in the POST-ajax action=login GET: %s' % r.status_code)
self.error = {'status':'bad status code', 'message':'bad status code received in the POST-ajax login action :' + str(r.status_code)}
return False
try:
j = r.json()
except:
logger.warn('Error - response from session-based skey check was not JSON: %s' % r.text)
return False
self.uid = j['response']['id']
self.authkey = j['response']['authkey']
self.passkey = pk = j['response']['passkey']
try:
d = self.ses.get('https://32pag.es/ajax.php', params={'action': 'user_inkdrops'}, verify=True, allow_redirects=True)
except Exception as e:
logger.error('Unable to retreive Inkdrop total : %s' % e)
else:
try:
self.inkdrops = d.json()
except:
logger.error('Inkdrop result did not return valid JSON, unable to verify response')
else:
logger.fdebug('inkdrops: %s' % self.inkdrops)
return True
def valid_login_attempt(self, un, pw):
'''
Does the actual POST to the login.php method (using the ajax parameter, which is far more reliable
than HTML parsing.
Input: un: The username (usually would be self.un, but that's not a requirement
pw: The password (usually self.pw but not a requirement)
Note: The underlying self.ses object will handle setting the session cookie from a valid login,
but you'll need to call the save method if your cookies are being persisted.
Returns: True (success) False (failure)
'''
postdata = {'username': un, 'password': pw, 'keeplogged': 1}
u = 'https://32pag.es/login.php?ajax=1'
try:
r = self.ses.post(u, data=postdata, timeout=60, allow_redirects=True)
logger.debug('%s Status Code: %s' % (self.module, r.status_code))
except Exception as e:
logger.error('%s Got an exception when trying to login: %s' % (self.module, e))
self.error = {'status':'exception', 'message':'Exception when trying to login'}
return False
if r.status_code != 200:
logger.warn('%s Got bad status code from login POST: %d\n%s\n%s' % (self.module, r.status_code, r.text, r.headers))
logger.debug('%s Request URL: %s \n Content: %s \n History: %s' % (self.module, r.url ,r.text, r.history))
self.error = {'status':'Bad Status code', 'message':(r.status_code, r.text, r.headers)}
return False
try:
logger.debug('%s Trying to analyze login JSON reply from 32P: %s' % (self.module, r.text))
d = r.json()
except:
logger.debug('%s Request URL: %s \n Content: %s \n History: %s' % (self.module, r.url ,r.text, r.history))
logger.error('%s The data returned by the login page was not JSON: %s' % (self.module, r.text))
self.error = {'status':'JSON not returned', 'message':r.text}
return False
if d['status'] == 'success':
return True
logger.error('%s Got unexpected status result: %s' % (self.module, d))
logger.debug('%s Request URL: %s \n Content: %s \n History: %s \n Json: %s' % (self.module, r.url ,r.text, r.history, d))
self.error = d
return False
def test_skey_valid(self, skey=None):
'''
You should call this method to test if the specified session key
(skey) is still valid. If skey is left out or None, it
automatically gets the value of the session cookie currently
set.
Returns: True (success) False (failure)
Side effects: Saves the cookies file.
'''
if skey is None:
skey = self.cookie_value('session', '')
if skey is None or skey == '':
return False
if (self.valid_skey_attempt(skey)):
self.ses.cookies.save(ignore_discard=True)
return True
self.ses.cookies.save(ignore_discard=True)
return False
def test_login(self):
'''
This is the method to call if you JUST want to login using self.un & self.pw
Note that this will generate a new session on 32pag.es every time you login successfully!
This is why the "keeplogged" option is only for when you persist cookies to disk.
Note that after a successful login, it will test the session key, which has the side effect of
getting the authkey,passkey & uid
Returns: True (login success) False (login failure)
Side Effects: On success: Sets the authkey, uid, passkey and saves the cookies to disk
(on failure): clears the cookies and saves that to disk.
'''
if (self.valid_login_attempt(self.un, self.pw)):
if self.cookie_exists('session'):
self.ses.cookies.save(ignore_discard=True)
if (not self.test_skey_valid()):
logger.error('Bad error: The attempt to get your attributes after successful login failed!')
self.error = {'status': 'Bad error', 'message': 'Attempt to get attributes after successful login failed.'}
return False
return True
logger.warn('Missing session cookie after successful login: %s' % self.ses.cookies)
self.ses.cookies.clear()
self.ses.cookies.save()
return False
def login(self):
'''
This is generally the only method you'll want to call, as it handles testing test_skey_valid() before
trying test_login().
Returns: True (success) / False (failure)
Side effects: Methods called will handle saving the cookies to disk, and setting
self.authkey, self.passkey, and self.uid
'''
if (self.test_skey_valid()):
logger.fdebug('%s Session key-based login was good.' % self.module)
self.method = 'Session Cookie retrieved OK.'
return {'ses': self.ses,
'status': True}
if (self.test_login()):
logger.fdebug('%s Credential-based login was good.' % self.module)
self.method = 'Credential-based login OK.'
return {'ses': self.ses,
'status': True}
logger.warn('%s Both session key and credential-based logins failed.' % self.module)
self.method = 'Both session key & credential login failed.'
return {'ses': self.ses,
'status': False}
#if __name__ == '__main__':
# ab = DoIt()
# c = ab.loadit()
| 32,382 | Python | .py | 573 | 40.324607 | 217 | 0.534263 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,266 | sabparse.py | evilhero_mylar/mylar/sabparse.py | #!/usr/bin/env python
# This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import mylar
from mylar import logger
import requests
from bs4 import BeautifulSoup, UnicodeDammit
import re
import datetime
import sys
from decimal import Decimal
from HTMLParser import HTMLParseError
from time import strptime
class sabnzbd(object):
def __init__(self, sabhost, sabusername, sabpassword):
self.sabhost = sabhost
self.sabusername = sabusername
self.sabpassword = sabpassword
def sab_get(self):
if self.sabusername is None or self.sabpassword is None:
logger.fdebug('No Username / Password specified for SABnzbd. Unable to auto-retrieve SAB API')
if 'https' not in self.sabhost:
self.sabhost = re.sub('http://', '', self.sabhost)
sabhttp = 'http://'
else:
self.sabhost = re.sub('https://', '', self.sabhost)
sabhttp = 'https://'
if not self.sabhost.endswith('/'):
self.sabhost = self.sabhost + '/'
sabline = sabhttp + str(self.sabhost)
with requests.Session() as s:
postdata = {'username': self.sabusername,
'password': self.sabpassword,
'remember_me': 0}
lo = s.post(sabline + 'login/', data=postdata, verify=False)
if not lo.status_code == 200:
return
r = s.get(sabline + 'config/general', verify=False)
soup = BeautifulSoup(r.content, "html.parser")
resultp = soup.findAll("div", {"class": "field-pair"})
for res in resultp:
if res.find("label", {"for": "apikey"}):
try:
result = res.find("input", {"type": "text"})
except:
continue
if result['id'] == "apikey":
apikey = result['value']
logger.fdebug('found SABnzbd APIKey: ' + str(apikey))
return apikey
if __name__ == '__main__':
test = sabnzbd()
test.sab_get()
| 2,727 | Python | .py | 65 | 33 | 106 | 0.606267 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,267 | ftpsshup.py | evilhero_mylar/mylar/ftpsshup.py | #!/usr/local/bin/python
import os
import time
import mylar
from mylar import logger
def putfile(localpath, file): #localpath=full path to .torrent (including filename), file=filename of torrent
try:
import paramiko
except ImportError:
logger.fdebug('paramiko not found on system. Please install manually in order to use seedbox option')
logger.fdebug('get it at https://github.com/paramiko/paramiko')
logger.fdebug('to install: python setup.py install')
logger.fdebug('aborting send.')
return "fail"
host = mylar.CONFIG.SEEDBOX_HOST
port = int(mylar.CONFIG.SEEDBOX_PORT) #this is usually 22
transport = paramiko.Transport((host, port))
logger.fdebug('Sending file: ' + str(file))
logger.fdebug('destination: ' + str(host))
logger.fdebug('Using SSH port : ' + str(port))
password = mylar.CONFIG.SEEDBOX_PASS
username = mylar.CONFIG.SEEDBOX_USER
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
import sys
if file[-7:] != "torrent":
file += ".torrent"
rempath = os.path.join(mylar.CONFIG.SEEDBOX_WATCHDIR, file) #this will default to the OS running mylar for slashes.
logger.fdebug('remote path set to ' + str(rempath))
logger.fdebug('local path set to ' + str(localpath))
if not os.path.exists(localpath):
logger.fdebug('file has not finished writing yet - pausing for 5s to allow for completion.')
time.sleep(5)
if not localpath.exists():
logger.fdebug('Skipping file at this time.')
return "fail"
sendcheck = False
while sendcheck == False:
try:
sftp.put(localpath, rempath)
sendcheck = True
except Exception, e:
logger.fdebug('ERROR Sending torrent to seedbox *** Caught exception: %s: %s' % (e.__class__, e))
logger.fdebug('Forcibly closing connection and attempting to reconnect')
sftp.close()
transport.close()
#reload the transport here cause it locked up previously.
transport = paramiko.Transport((host, port))
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
logger.fdebug('sucessfully reconnected via sftp - attempting to resend.')
#return "fail"
sftp.close()
transport.close()
logger.fdebug('Upload complete to seedbox.')
return "pass"
def sendfiles(filelist):
try:
import paramiko
except ImportError:
logger.fdebug('paramiko not found on system. Please install manually in order to use seedbox option')
logger.fdebug('get it at https://github.com/paramiko/paramiko')
logger.fdebug('to install: python setup.py install')
logger.fdebug('aborting send.')
return
fhost = mylar.CONFIG.TAB_HOST.find(':')
host = mylar.CONFIG.TAB_HOST[:fhost]
port = int(mylar.CONFIG.TAB_HOST[fhost +1:])
logger.fdebug('Destination: ' + host)
logger.fdebug('Using SSH port : ' + str(port))
transport = paramiko.Transport((host, port))
password = mylar.CONFIG.TAB_PASS
username = mylar.CONFIG.TAB_USER
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
remotepath = mylar.CONFIG.TAB_DIRECTORY
logger.fdebug('remote path set to ' + remotepath)
if len(filelist) > 0:
logger.info('Initiating send for ' + str(len(filelist)) + ' files...')
return sendtohome(sftp, remotepath, filelist, transport)
def sendtohome(sftp, remotepath, filelist, transport):
fhost = mylar.CONFIG.TAB_HOST.find(':')
host = mylar.CONFIG.TAB_HOST[:fhost]
port = int(mylar.CONFIG.TAB_HOST[fhost +1:])
successlist = []
filestotal = len(filelist)
for files in filelist:
tempfile = files['filename']
issid = files['issueid']
logger.fdebug('Checking filename for problematic characters: ' + tempfile)
#we need to make the required directory(ies)/subdirectories before the get will work.
if u'\xb4' in files['filename']:
# right quotation
logger.fdebug('detected abnormal character in filename')
filename = tempfile.replace('0xb4', '\'')
if u'\xbd' in files['filename']:
# 1/2 character
filename = tempfile.replace('0xbd', 'half')
if u'\uff1a' in files['filename']:
#some unknown character
filename = tempfile.replace('\0ff1a', '-')
#now we encode the structure to ascii so we can write directories/filenames without error.
filename = tempfile.encode('ascii', 'ignore')
remdir = remotepath
if mylar.CONFIG.MAINTAINSERIESFOLDER == 1:
# Get folder path of issue
comicdir = os.path.split(files['filepath'])[0]
# Isolate comic folder name
comicdir = os.path.split(comicdir)[1]
logger.info('Checking for Comic Folder: ' + comicdir)
chkdir = os.path.join(remdir, comicdir)
try:
sftp.stat(chkdir)
except IOError, e:
logger.info('Comic Folder does not Exist, creating ' + chkdir )
try:
sftp.mkdir(chkdir)
except :
# Fallback to default behavior
logger.info('Could not create Comic Folder, adding to device root')
else :
remdir = chkdir
else :
remdir = chkdir
localsend = files['filepath']
logger.info('Sending : ' + localsend)
remotesend = os.path.join(remdir, filename)
logger.info('To : ' + remotesend)
try:
sftp.stat(remotesend)
except IOError, e:
if e[0] == 2:
filechk = False
else:
filechk = True
if not filechk:
sendcheck = False
count = 1
while sendcheck == False:
try:
sftp.put(localsend, remotesend)#, callback=printTotals)
sendcheck = True
except Exception, e:
logger.info('Attempt #' + str(count) + ': ERROR Sending issue to seedbox *** Caught exception: %s: %s' % (e.__class__, e))
logger.info('Forcibly closing connection and attempting to reconnect')
sftp.close()
transport.close()
#reload the transport here cause it locked up previously.
transport = paramiko.Transport((host, port))
transport.connect(username=mylar.CONFIG.TAB_USER, password=mylar.CONFIG.TAB_PASS)
sftp = paramiko.SFTPClient.from_transport(transport)
count+=1
if count > 5:
break
if count > 5:
logger.info('Unable to send - tried 5 times and failed. Aborting entire process.')
break
else:
logger.info('file already exists - checking if complete or not.')
filesize = sftp.stat(remotesend).st_size
if not filesize == os.path.getsize(files['filepath']):
logger.info('file not complete - attempting to resend')
sendcheck = False
count = 1
while sendcheck == False:
try:
sftp.put(localsend, remotesend)
sendcheck = True
except Exception, e:
logger.info('Attempt #' + str(count) + ': ERROR Sending issue to seedbox *** Caught exception: %s: %s' % (e.__class__, e))
logger.info('Forcibly closing connection and attempting to reconnect')
sftp.close()
transport.close()
#reload the transport here cause it locked up previously.
transport = paramiko.Transport((host, port))
transport.connect(username=mylar.CONFIG.TAB_USER, password=mylar.CONFIG.TAB_PASS)
sftp = paramiko.SFTPClient.from_transport(transport)
count+=1
if count > 5:
break
if count > 5:
logger.info('Unable to send - tried 5 times and failed. Aborting entire process.')
break
else:
logger.info('file 100% complete according to byte comparison.')
logger.info('Marking as being successfully Downloaded to 3rd party device (Queuing to change Read Status to Downloaded)')
successlist.append({"issueid": issid})
sftp.close()
transport.close()
logger.fdebug('Upload of readlist complete.')
return successlist
#def printTotals(transferred, toBeTransferred):
# percent = transferred / toBeTransferred
# logger.info("Transferred: " + str(transferred) + " Out of " + str(toBeTransferred))
#if __name__ == '__main__':
# putfile(sys.argv[1])
| 9,292 | Python | .py | 196 | 35.816327 | 146 | 0.597681 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,268 | helpers.py | evilhero_mylar/mylar/helpers.py | # This file is part of Mylar.
# -*- coding: utf-8 -*-
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import time
from operator import itemgetter
import datetime
from datetime import timedelta, date
import subprocess
import requests
import shlex
import Queue
import json
import re
import sys
import ctypes
import platform
import calendar
import itertools
import shutil
import hashlib
import gzip
import os, errno
from StringIO import StringIO
from apscheduler.triggers.interval import IntervalTrigger
import mylar
import logger
from mylar import db, sabnzbd, nzbget, process, getcomics
def multikeysort(items, columns):
comparers = [((itemgetter(col[1:].strip()), -1) if col.startswith('-') else (itemgetter(col.strip()), 1)) for col in columns]
def comparer(left, right):
for fn, mult in comparers:
result = cmp(fn(left), fn(right))
if result:
return mult * result
else:
return 0
return sorted(items, cmp=comparer)
def checked(variable):
if variable:
return 'Checked'
else:
return ''
def radio(variable, pos):
if variable == pos:
return 'Checked'
else:
return ''
def latinToAscii(unicrap):
"""
From couch potato
"""
xlate = {0xc0: 'A', 0xc1: 'A', 0xc2: 'A', 0xc3: 'A', 0xc4: 'A', 0xc5: 'A',
0xc6: 'Ae', 0xc7: 'C',
0xc8: 'E', 0xc9: 'E', 0xca: 'E', 0xcb: 'E', 0x86: 'e',
0xcc: 'I', 0xcd: 'I', 0xce: 'I', 0xcf: 'I',
0xd0: 'Th', 0xd1: 'N',
0xd2: 'O', 0xd3: 'O', 0xd4: 'O', 0xd5: 'O', 0xd6: 'O', 0xd8: 'O',
0xd9: 'U', 0xda: 'U', 0xdb: 'U', 0xdc: 'U',
0xdd: 'Y', 0xde: 'th', 0xdf: 'ss',
0xe0: 'a', 0xe1: 'a', 0xe2: 'a', 0xe3: 'a', 0xe4: 'a', 0xe5: 'a',
0xe6: 'ae', 0xe7: 'c',
0xe8: 'e', 0xe9: 'e', 0xea: 'e', 0xeb: 'e', 0x0259: 'e',
0xec: 'i', 0xed: 'i', 0xee: 'i', 0xef: 'i',
0xf0: 'th', 0xf1: 'n',
0xf2: 'o', 0xf3: 'o', 0xf4: 'o', 0xf5: 'o', 0xf6: 'o', 0xf8: 'o',
0xf9: 'u', 0xfa: 'u', 0xfb: 'u', 0xfc: 'u',
0xfd: 'y', 0xfe: 'th', 0xff: 'y',
0xa1: '!', 0xa2: '{cent}', 0xa3: '{pound}', 0xa4: '{currency}',
0xa5: '{yen}', 0xa6: '|', 0xa7: '{section}', 0xa8: '{umlaut}',
0xa9: '{C}', 0xaa: '{^a}', 0xab: '<<', 0xac: '{not}',
0xad: '-', 0xae: '{R}', 0xaf: '_', 0xb0: '{degrees}',
0xb1: '{+/-}', 0xb2: '{^2}', 0xb3: '{^3}', 0xb4: "'",
0xb5: '{micro}', 0xb6: '{paragraph}', 0xb7: '*', 0xb8: '{cedilla}',
0xb9: '{^1}', 0xba: '{^o}', 0xbb: '>>',
0xbc: '{1/4}', 0xbd: '{1/2}', 0xbe: '{3/4}', 0xbf: '?',
0xd7: '*', 0xf7: '/'
}
r = ''
for i in unicrap:
if xlate.has_key(ord(i)):
r += xlate[ord(i)]
elif ord(i) >= 0x80:
pass
else:
r += str(i)
return r
def convert_milliseconds(ms):
seconds = ms /1000
gmtime = time.gmtime(seconds)
if seconds > 3600:
minutes = time.strftime("%H:%M:%S", gmtime)
else:
minutes = time.strftime("%M:%S", gmtime)
return minutes
def convert_seconds(s):
gmtime = time.gmtime(s)
if s > 3600:
minutes = time.strftime("%H:%M:%S", gmtime)
else:
minutes = time.strftime("%M:%S", gmtime)
return minutes
def today():
today = datetime.date.today()
yyyymmdd = datetime.date.isoformat(today)
return yyyymmdd
def now():
now = datetime.datetime.now()
return now.strftime("%Y-%m-%d %H:%M:%S")
def utctimestamp():
return time.time()
def bytes_to_mb(bytes):
mb = int(bytes) /1048576
size = '%.1f MB' % mb
return size
def human_size(size_bytes):
"""
format a size in bytes into a 'human' file size, e.g. bytes, KB, MB, GB, TB, PB
Note that bytes/KB will be reported in whole numbers but MB and above will have greater precision
e.g. 1 byte, 43 bytes, 443 KB, 4.3 MB, 4.43 GB, etc
"""
if size_bytes == 1:
# because I really hate unnecessary plurals
return "1 byte"
suffixes_table = [('bytes', 0), ('KB', 0), ('MB', 1), ('GB', 2), ('TB', 2), ('PB', 2)]
num = float(0 if size_bytes is None else size_bytes)
for suffix, precision in suffixes_table:
if num < 1024.0:
break
num /= 1024.0
if precision == 0:
formatted_size = "%d" % num
else:
formatted_size = str(round(num, ndigits=precision))
return "%s %s" % (formatted_size, suffix)
def human2bytes(s):
"""
>>> human2bytes('1M')
1048576
>>> human2bytes('1G')
1073741824
"""
symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
letter = s[-1:].strip().upper()
num = re.sub(',', '', s[:-1])
#assert num.isdigit() and letter in symbols
#use below assert statement to handle sizes with decimal places
if num != '0':
assert float(num) and letter in symbols
num = float(num)
prefix = {symbols[0]: 1}
for i, s in enumerate(symbols[1:]):
prefix[s] = 1 << (i +1) *10
return int(num * prefix[letter])
else:
return 0
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text.rstrip()
def cleanName(string):
pass1 = latinToAscii(string).lower()
out_string = re.sub('[\/\@\#\$\%\^\*\+\"\[\]\{\}\<\>\=\_]', ' ', pass1).encode('utf-8')
return out_string
def cleanTitle(title):
title = re.sub('[\.\-\/\_]', ' ', title).lower()
# Strip out extra whitespace
title = ' '.join(title.split())
title = title.title()
return title
def extract_logline(s):
# Default log format
pattern = re.compile(r'(?P<timestamp>.*?)\s\-\s(?P<level>.*?)\s*\:\:\s(?P<thread>.*?)\s\:\s(?P<message>.*)', re.VERBOSE)
match = pattern.match(s)
if match:
timestamp = match.group("timestamp")
level = match.group("level")
thread = match.group("thread")
message = match.group("message")
return (timestamp, level, thread, message)
else:
return None
def is_number(s):
try:
float(s)
except (ValueError, TypeError):
return False
else:
return True
def decimal_issue(iss):
iss_find = iss.find('.')
dec_except = None
if iss_find == -1:
#no matches for a decimal, assume we're converting from decimal to int.
#match for special issues with alphanumeric numbering...
if 'au' in iss.lower():
dec_except = 'AU'
decex = iss.lower().find('au')
deciss = int(iss[:decex]) * 1000
else:
deciss = int(iss) * 1000
else:
iss_b4dec = iss[:iss_find]
iss_decval = iss[iss_find +1:]
if int(iss_decval) == 0:
iss = iss_b4dec
issdec = int(iss_decval)
else:
if len(iss_decval) == 1:
iss = iss_b4dec + "." + iss_decval
issdec = int(iss_decval) * 10
else:
iss = iss_b4dec + "." + iss_decval.rstrip('0')
issdec = int(iss_decval.rstrip('0')) * 10
deciss = (int(iss_b4dec) * 1000) + issdec
return deciss, dec_except
def rename_param(comicid, comicname, issue, ofilename, comicyear=None, issueid=None, annualize=None, arc=False):
#import db
myDB = db.DBConnection()
comicid = str(comicid) # it's coming in unicoded...
logger.fdebug(type(comicid))
logger.fdebug(type(issueid))
logger.fdebug('comicid: %s' % comicid)
logger.fdebug('issue# as per cv: %s' % issue)
# the issue here is a non-decimalized version, we need to see if it's got a decimal and if not, add '.00'
# iss_find = issue.find('.')
# if iss_find < 0:
# # no decimal in issue number
# iss = str(int(issue)) + ".00"
# else:
# iss_b4dec = issue[:iss_find]
# iss_decval = issue[iss_find+1:]
# if len(str(int(iss_decval))) == 1:
# iss = str(int(iss_b4dec)) + "." + str(int(iss_decval)*10)
# else:
# if issue.endswith(".00"):
# iss = issue
# else:
# iss = str(int(iss_b4dec)) + "." + iss_decval
# issue = iss
# print ("converted issue#: " + str(issue))
logger.fdebug('issueid:' + str(issueid))
if issueid is None:
logger.fdebug('annualize is ' + str(annualize))
if arc:
#this has to be adjusted to be able to include story arc issues that span multiple arcs
chkissue = myDB.selectone("SELECT * from storyarcs WHERE ComicID=? AND Issue_Number=?", [comicid, issue]).fetchone()
else:
chkissue = myDB.selectone("SELECT * from issues WHERE ComicID=? AND Issue_Number=?", [comicid, issue]).fetchone()
if all([chkissue is None, annualize is None, not mylar.CONFIG.ANNUALS_ON]):
chkissue = myDB.selectone("SELECT * from annuals WHERE ComicID=? AND Issue_Number=?", [comicid, issue]).fetchone()
if chkissue is None:
#rechk chkissue against int value of issue #
if arc:
chkissue = myDB.selectone("SELECT * from storyarcs WHERE ComicID=? AND Int_IssueNumber=?", [comicid, issuedigits(issue)]).fetchone()
else:
chkissue = myDB.selectone("SELECT * from issues WHERE ComicID=? AND Int_IssueNumber=?", [comicid, issuedigits(issue)]).fetchone()
if all([chkissue is None, annualize == 'yes', mylar.CONFIG.ANNUALS_ON]):
chkissue = myDB.selectone("SELECT * from annuals WHERE ComicID=? AND Int_IssueNumber=?", [comicid, issuedigits(issue)]).fetchone()
if chkissue is None:
logger.error('Invalid Issue_Number - please validate.')
return
else:
logger.info('Int Issue_number compare found. continuing...')
issueid = chkissue['IssueID']
else:
issueid = chkissue['IssueID']
#use issueid to get publisher, series, year, issue number
logger.fdebug('issueid is now : ' + str(issueid))
if arc:
issuenzb = myDB.selectone("SELECT * from storyarcs WHERE ComicID=? AND IssueID=? AND StoryArc=?", [comicid, issueid, arc]).fetchone()
else:
issuenzb = myDB.selectone("SELECT * from issues WHERE ComicID=? AND IssueID=?", [comicid, issueid]).fetchone()
if issuenzb is None:
logger.fdebug('not an issue, checking against annuals')
issuenzb = myDB.selectone("SELECT * from annuals WHERE ComicID=? AND IssueID=?", [comicid, issueid]).fetchone()
if issuenzb is None:
logger.fdebug('Unable to rename - cannot locate issue id within db')
return
else:
annualize = True
if issuenzb is None:
logger.fdebug('Unable to rename - cannot locate issue id within db')
return
#remap the variables to a common factor.
if arc:
issuenum = issuenzb['IssueNumber']
issuedate = issuenzb['IssueDate']
publisher = issuenzb['IssuePublisher']
series = issuenzb['ComicName']
seriesfilename = series #Alternate FileNaming is not available with story arcs.
seriesyear = issuenzb['SeriesYear']
arcdir = filesafe(issuenzb['StoryArc'])
if mylar.CONFIG.REPLACE_SPACES:
arcdir = arcdir.replace(' ', mylar.CONFIG.REPLACE_CHAR)
if mylar.CONFIG.STORYARCDIR:
storyarcd = os.path.join(mylar.CONFIG.DESTINATION_DIR, "StoryArcs", arcdir)
logger.fdebug('Story Arc Directory set to : ' + storyarcd)
else:
logger.fdebug('Story Arc Directory set to : ' + mylar.CONFIG.GRABBAG_DIR)
storyarcd = os.path.join(mylar.CONFIG.DESTINATION_DIR, mylar.CONFIG.GRABBAG_DIR)
comlocation = storyarcd
comversion = None #need to populate this.
else:
issuenum = issuenzb['Issue_Number']
issuedate = issuenzb['IssueDate']
comicnzb= myDB.selectone("SELECT * from comics WHERE comicid=?", [comicid]).fetchone()
publisher = comicnzb['ComicPublisher']
series = comicnzb['ComicName']
if comicnzb['AlternateFileName'] is None or comicnzb['AlternateFileName'] == 'None':
seriesfilename = series
else:
seriesfilename = comicnzb['AlternateFileName']
logger.fdebug('Alternate File Naming has been enabled for this series. Will rename series title to : ' + seriesfilename)
seriesyear = comicnzb['ComicYear']
comlocation = comicnzb['ComicLocation']
comversion = comicnzb['ComicVersion']
unicodeissue = issuenum
if type(issuenum) == unicode:
vals = {u'\xbd':'.5',u'\xbc':'.25',u'\xbe':'.75',u'\u221e':'9999999999',u'\xe2':'9999999999'}
else:
vals = {'\xbd':'.5','\xbc':'.25','\xbe':'.75','\u221e':'9999999999','\xe2':'9999999999'}
x = [vals[key] for key in vals if key in issuenum]
if x:
issuenum = x[0]
logger.fdebug('issue number formatted: %s' % issuenum)
#comicid = issuenzb['ComicID']
#issueno = str(issuenum).split('.')[0]
issue_except = 'None'
issue_exceptions = ['AU',
'INH',
'NOW',
'AI',
'MU',
'HU',
'A',
'B',
'C',
'X',
'O']
valid_spaces = ('.', '-')
for issexcept in issue_exceptions:
if issexcept.lower() in issuenum.lower():
logger.fdebug('ALPHANUMERIC EXCEPTION : [' + issexcept + ']')
v_chk = [v for v in valid_spaces if v in issuenum]
if v_chk:
iss_space = v_chk[0]
logger.fdebug('character space denoted as : ' + iss_space)
else:
logger.fdebug('character space not denoted.')
iss_space = ''
# if issexcept == 'INH':
# issue_except = '.INH'
if issexcept == 'NOW':
if '!' in issuenum: issuenum = re.sub('\!', '', issuenum)
# issue_except = '.NOW'
issue_except = iss_space + issexcept
logger.fdebug('issue_except denoted as : ' + issue_except)
issuenum = re.sub("[^0-9]", "", issuenum)
break
# if 'au' in issuenum.lower() and issuenum[:1].isdigit():
# issue_except = ' AU'
# elif 'ai' in issuenum.lower() and issuenum[:1].isdigit():
# issuenum = re.sub("[^0-9]", "", issuenum)
# issue_except = ' AI'
# elif 'inh' in issuenum.lower() and issuenum[:1].isdigit():
# issuenum = re.sub("[^0-9]", "", issuenum)
# issue_except = '.INH'
# elif 'now' in issuenum.lower() and issuenum[:1].isdigit():
# if '!' in issuenum: issuenum = re.sub('\!', '', issuenum)
# issuenum = re.sub("[^0-9]", "", issuenum)
# issue_except = '.NOW'
if '.' in issuenum:
iss_find = issuenum.find('.')
iss_b4dec = issuenum[:iss_find]
if iss_find == 0:
iss_b4dec = '0'
iss_decval = issuenum[iss_find +1:]
if iss_decval.endswith('.'):
iss_decval = iss_decval[:-1]
if int(iss_decval) == 0:
iss = iss_b4dec
issdec = int(iss_decval)
issueno = iss
else:
if len(iss_decval) == 1:
iss = iss_b4dec + "." + iss_decval
issdec = int(iss_decval) * 10
else:
iss = iss_b4dec + "." + iss_decval.rstrip('0')
issdec = int(iss_decval.rstrip('0')) * 10
issueno = iss_b4dec
else:
iss = issuenum
issueno = iss
# issue zero-suppression here
if mylar.CONFIG.ZERO_LEVEL == "0":
zeroadd = ""
else:
if mylar.CONFIG.ZERO_LEVEL_N == "none": zeroadd = ""
elif mylar.CONFIG.ZERO_LEVEL_N == "0x": zeroadd = "0"
elif mylar.CONFIG.ZERO_LEVEL_N == "00x": zeroadd = "00"
logger.fdebug('Zero Suppression set to : ' + str(mylar.CONFIG.ZERO_LEVEL_N))
prettycomiss = None
if issueno.isalpha():
logger.fdebug('issue detected as an alpha.')
prettycomiss = str(issueno)
else:
try:
x = float(issuenum)
#validity check
if x < 0:
logger.info('I\'ve encountered a negative issue #: %s. Trying to accomodate.' % issueno)
prettycomiss = '-' + str(zeroadd) + str(issueno[1:])
elif x == 9999999999:
logger.fdebug('Infinity issue found.')
issuenum = 'infinity'
elif x >= 0:
pass
else:
raise ValueError
except ValueError, e:
logger.warn('Unable to properly determine issue number [ %s] - you should probably log this on github for help.' % issueno)
return
if prettycomiss is None and len(str(issueno)) > 0:
#if int(issueno) < 0:
# self._log("issue detected is a negative")
# prettycomiss = '-' + str(zeroadd) + str(abs(issueno))
if int(issueno) < 10:
logger.fdebug('issue detected less than 10')
if '.' in iss:
if int(iss_decval) > 0:
issueno = str(iss)
prettycomiss = str(zeroadd) + str(iss)
else:
prettycomiss = str(zeroadd) + str(int(issueno))
else:
prettycomiss = str(zeroadd) + str(iss)
if issue_except != 'None':
prettycomiss = str(prettycomiss) + issue_except
logger.fdebug('Zero level supplement set to ' + str(mylar.CONFIG.ZERO_LEVEL_N) + '. Issue will be set as : ' + str(prettycomiss))
elif int(issueno) >= 10 and int(issueno) < 100:
logger.fdebug('issue detected greater than 10, but less than 100')
if mylar.CONFIG.ZERO_LEVEL_N == "none":
zeroadd = ""
else:
zeroadd = "0"
if '.' in iss:
if int(iss_decval) > 0:
issueno = str(iss)
prettycomiss = str(zeroadd) + str(iss)
else:
prettycomiss = str(zeroadd) + str(int(issueno))
else:
prettycomiss = str(zeroadd) + str(iss)
if issue_except != 'None':
prettycomiss = str(prettycomiss) + issue_except
logger.fdebug('Zero level supplement set to ' + str(mylar.CONFIG.ZERO_LEVEL_N) + '.Issue will be set as : ' + str(prettycomiss))
else:
logger.fdebug('issue detected greater than 100')
if issuenum == 'infinity':
prettycomiss = 'infinity'
else:
if '.' in iss:
if int(iss_decval) > 0:
issueno = str(iss)
prettycomiss = str(issueno)
if issue_except != 'None':
prettycomiss = str(prettycomiss) + issue_except
logger.fdebug('Zero level supplement set to ' + str(mylar.CONFIG.ZERO_LEVEL_N) + '. Issue will be set as : ' + str(prettycomiss))
elif len(str(issueno)) == 0:
prettycomiss = str(issueno)
logger.fdebug('issue length error - cannot determine length. Defaulting to None: ' + str(prettycomiss))
logger.fdebug('Pretty Comic Issue is : ' + str(prettycomiss))
if mylar.CONFIG.UNICODE_ISSUENUMBER:
logger.fdebug('Setting this to Unicode format as requested: %s' % prettycomiss)
prettycomiss = unicodeissue
issueyear = issuedate[:4]
month = issuedate[5:7].replace('-', '').strip()
month_name = fullmonth(month)
if month_name is None:
month_name = 'None'
logger.fdebug('Issue Year : ' + str(issueyear))
logger.fdebug('Publisher: ' + publisher)
logger.fdebug('Series: ' + series)
logger.fdebug('Year: ' + str(seriesyear))
logger.fdebug('Comic Location: ' + comlocation)
if comversion is None:
comversion = 'None'
#if comversion is None, remove it so it doesn't populate with 'None'
if comversion == 'None':
chunk_f_f = re.sub('\$VolumeN', '', mylar.CONFIG.FILE_FORMAT)
chunk_f = re.compile(r'\s+')
chunk_file_format = chunk_f.sub(' ', chunk_f_f)
logger.fdebug('No version # found for series, removing from filename')
logger.fdebug("new format: " + str(chunk_file_format))
else:
chunk_file_format = mylar.CONFIG.FILE_FORMAT
if annualize is None:
chunk_f_f = re.sub('\$Annual', '', chunk_file_format)
chunk_f = re.compile(r'\s+')
chunk_file_format = chunk_f.sub(' ', chunk_f_f)
logger.fdebug('not an annual - removing from filename paramaters')
logger.fdebug('new format: ' + str(chunk_file_format))
else:
logger.fdebug('chunk_file_format is: ' + str(chunk_file_format))
if mylar.CONFIG.ANNUALS_ON:
if 'annual' in series.lower():
if '$Annual' not in chunk_file_format: # and 'annual' not in ofilename.lower():
#if it's an annual, but $annual isn't specified in file_format, we need to
#force it in there, by default in the format of $Annual $Issue
#prettycomiss = "Annual " + str(prettycomiss)
logger.fdebug('[%s][ANNUALS-ON][ANNUAL IN SERIES][NO ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
#because it exists within title, strip it then use formatting tag for placement of wording.
chunk_f_f = re.sub('\$Annual', '', chunk_file_format)
chunk_f = re.compile(r'\s+')
chunk_file_format = chunk_f.sub(' ', chunk_f_f)
logger.fdebug('[%s][ANNUALS-ON][ANNUAL IN SERIES][ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
if '$Annual' not in chunk_file_format: # and 'annual' not in ofilename.lower():
#if it's an annual, but $annual isn't specified in file_format, we need to
#force it in there, by default in the format of $Annual $Issue
prettycomiss = "Annual %s" % prettycomiss
logger.fdebug('[%s][ANNUALS-ON][ANNUAL NOT IN SERIES][NO ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
logger.fdebug('[%s][ANNUALS-ON][ANNUAL NOT IN SERIES][ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
#if annuals aren't enabled, then annuals are being tracked as independent series.
#annualize will be true since it's an annual in the seriesname.
if 'annual' in series.lower():
if '$Annual' not in chunk_file_format: # and 'annual' not in ofilename.lower():
#if it's an annual, but $annual isn't specified in file_format, we need to
#force it in there, by default in the format of $Annual $Issue
#prettycomiss = "Annual " + str(prettycomiss)
logger.fdebug('[%s][ANNUALS-OFF][ANNUAL IN SERIES][NO ANNUAL FORMAT] prettycomiss: %s' (series, prettycomiss))
else:
#because it exists within title, strip it then use formatting tag for placement of wording.
chunk_f_f = re.sub('\$Annual', '', chunk_file_format)
chunk_f = re.compile(r'\s+')
chunk_file_format = chunk_f.sub(' ', chunk_f_f)
logger.fdebug('[%s][ANNUALS-OFF][ANNUAL IN SERIES][ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
if '$Annual' not in chunk_file_format: # and 'annual' not in ofilename.lower():
#if it's an annual, but $annual isn't specified in file_format, we need to
#force it in there, by default in the format of $Annual $Issue
prettycomiss = "Annual %s" % prettycomiss
logger.fdebug('[%s][ANNUALS-OFF][ANNUAL NOT IN SERIES][NO ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
else:
logger.fdebug('[%s][ANNUALS-OFF][ANNUAL NOT IN SERIES][ANNUAL FORMAT] prettycomiss: %s' % (series, prettycomiss))
logger.fdebug('Annual detected within series title of ' + series + '. Not auto-correcting issue #')
seriesfilename = seriesfilename.encode('ascii', 'ignore').strip()
filebad = [':', ',', '/', '?', '!', '\'', '\"', '\*'] #in u_comicname or '/' in u_comicname or ',' in u_comicname or '?' in u_comicname:
for dbd in filebad:
if dbd in seriesfilename:
if any([dbd == '/', dbd == '*']):
repthechar = '-'
else:
repthechar = ''
seriesfilename = seriesfilename.replace(dbd, repthechar)
logger.fdebug('Altering series name due to filenaming restrictions: ' + seriesfilename)
publisher = re.sub('!', '', publisher)
file_values = {'$Series': seriesfilename,
'$Issue': prettycomiss,
'$Year': issueyear,
'$series': series.lower(),
'$Publisher': publisher,
'$publisher': publisher.lower(),
'$VolumeY': 'V' + str(seriesyear),
'$VolumeN': comversion,
'$monthname': month_name,
'$month': month,
'$Annual': 'Annual'
}
extensions = ('.cbr', '.cbz', '.cb7')
if ofilename.lower().endswith(extensions):
path, ext = os.path.splitext(ofilename)
if mylar.CONFIG.FILE_FORMAT == '':
logger.fdebug('Rename Files is not enabled - keeping original filename.')
#check if extension is in nzb_name - will screw up otherwise
if ofilename.lower().endswith(extensions):
nfilename = ofilename[:-4]
else:
nfilename = ofilename
else:
nfilename = replace_all(chunk_file_format, file_values)
if mylar.CONFIG.REPLACE_SPACES:
#mylar.CONFIG.REPLACE_CHAR ...determines what to replace spaces with underscore or dot
nfilename = nfilename.replace(' ', mylar.CONFIG.REPLACE_CHAR)
nfilename = re.sub('[\,\:]', '', nfilename) + ext.lower()
logger.fdebug('New Filename: ' + nfilename)
if mylar.CONFIG.LOWERCASE_FILENAMES:
nfilename = nfilename.lower()
dst = os.path.join(comlocation, nfilename)
else:
dst = os.path.join(comlocation, nfilename)
logger.fdebug('Source: ' + ofilename)
logger.fdebug('Destination: ' + dst)
rename_this = {"destination_dir": dst,
"nfilename": nfilename,
"issueid": issueid,
"comicid": comicid}
return rename_this
def apiremove(apistring, type):
if type == 'nzb':
value_regex = re.compile("(?<=apikey=)(?P<value>.*?)(?=$)")
#match = value_regex.search(apistring)
apiremoved = value_regex.sub("xUDONTNEEDTOKNOWTHISx", apistring)
else:
#type = $ to denote end of string
#type = & to denote up until next api variable
value_regex1 = re.compile("(?<=%26i=1%26r=)(?P<value>.*?)(?=" + str(type) +")")
#match = value_regex.search(apistring)
apiremoved1 = value_regex1.sub("xUDONTNEEDTOKNOWTHISx", apistring)
value_regex = re.compile("(?<=apikey=)(?P<value>.*?)(?=" + str(type) +")")
apiremoved = value_regex.sub("xUDONTNEEDTOKNOWTHISx", apiremoved1)
#need to remove the urlencoded-portions as well in future
return apiremoved
def remove_apikey(payd, key):
#payload = some dictionary with payload values
#key = the key to replace with REDACTED (normally apikey)
for k,v in payd.items():
payd[key] = 'REDACTED'
return payd
def ComicSort(comicorder=None, sequence=None, imported=None):
if sequence:
# if it's on startup, load the sql into a tuple for use to avoid record-locking
i = 0
#import db
myDB = db.DBConnection()
comicsort = myDB.select("SELECT * FROM comics ORDER BY ComicSortName COLLATE NOCASE")
comicorderlist = []
comicorder = {}
comicidlist = []
if sequence == 'update':
mylar.COMICSORT['SortOrder'] = None
mylar.COMICSORT['LastOrderNo'] = None
mylar.COMICSORT['LastOrderID'] = None
for csort in comicsort:
if csort['ComicID'] is None: pass
if not csort['ComicID'] in comicidlist:
if sequence == 'startup':
comicorderlist.append({
'ComicID': csort['ComicID'],
'ComicOrder': i
})
elif sequence == 'update':
comicorderlist.append({
# mylar.COMICSORT['SortOrder'].append({
'ComicID': csort['ComicID'],
'ComicOrder': i
})
comicidlist.append(csort['ComicID'])
i+=1
if sequence == 'startup':
if i == 0:
comicorder['SortOrder'] = ({'ComicID': '99999', 'ComicOrder': 1})
comicorder['LastOrderNo'] = 1
comicorder['LastOrderID'] = 99999
else:
comicorder['SortOrder'] = comicorderlist
comicorder['LastOrderNo'] = i -1
comicorder['LastOrderID'] = comicorder['SortOrder'][i -1]['ComicID']
if i < 0: i == 0
logger.info('Sucessfully ordered ' + str(i -1) + ' series in your watchlist.')
return comicorder
elif sequence == 'update':
mylar.COMICSORT['SortOrder'] = comicorderlist
#print ("i:" + str(i))
if i == 0:
placemnt = 1
else:
placemnt = int(i -1)
mylar.COMICSORT['LastOrderNo'] = placemnt
mylar.COMICSORT['LastOrderID'] = mylar.COMICSORT['SortOrder'][placemnt]['ComicID']
return
else:
# for new series adds, we already know the comicid, so we set the sortorder to an abnormally high #
# we DO NOT write to the db to avoid record-locking.
# if we get 2 999's we're in trouble though.
sortedapp = []
if comicorder['LastOrderNo'] == '999':
lastorderval = int(comicorder['LastOrderNo']) + 1
else:
lastorderval = 999
sortedapp.append({
'ComicID': imported,
'ComicOrder': lastorderval
})
mylar.COMICSORT['SortOrder'] = sortedapp
mylar.COMICSORT['LastOrderNo'] = lastorderval
mylar.COMICSORT['LastOrderID'] = imported
return
def fullmonth(monthno):
#simple numerical to worded month conversion....
basmonths = {'1': 'January', '2': 'February', '3': 'March', '4': 'April', '5': 'May', '6': 'June', '7': 'July', '8': 'August', '9': 'September', '10': 'October', '11': 'November', '12': 'December'}
monthconv = None
for numbs in basmonths:
if int(numbs) == int(monthno):
monthconv = basmonths[numbs]
return monthconv
def updateComicLocation():
#in order for this to work, the ComicLocation MUST be left at the original location.
#in the config.ini - set LOCMOVE = 1 (to enable this to run on the NEXT startup)
# - set NEWCOMDIR = new ComicLocation
#after running, set ComicLocation to new location in Configuration GUI
#import db
myDB = db.DBConnection()
if mylar.CONFIG.NEWCOM_DIR is not None:
logger.info('Performing a one-time mass update to Comic Location')
#create the root dir if it doesn't exist
checkdirectory = mylar.filechecker.validateAndCreateDirectory(mylar.CONFIG.NEWCOM_DIR, create=True)
if not checkdirectory:
logger.warn('Error trying to validate/create directory. Aborting this process at this time.')
return
dirlist = myDB.select("SELECT * FROM comics")
comloc = []
if dirlist is not None:
for dl in dirlist:
u_comicnm = dl['ComicName']
# let's remove the non-standard characters here that will break filenaming / searching.
comicname_folder = filesafe(u_comicnm)
publisher = re.sub('!', '', dl['ComicPublisher']) # thanks Boom!
year = dl['ComicYear']
if dl['Corrected_Type'] is not None:
booktype = dl['Corrected_Type']
else:
booktype = dl['Type']
if booktype == 'Print' or all([booktype != 'Print', mylar.CONFIG.FORMAT_BOOKTYPE is False]):
chunk_fb = re.sub('\$Type', '', mylar.CONFIG.FOLDER_FORMAT)
chunk_b = re.compile(r'\s+')
chunk_folder_format = chunk_b.sub(' ', chunk_fb)
else:
chunk_folder_format = mylar.CONFIG.FOLDER_FORMAT
comversion = dl['ComicVersion']
if comversion is None:
comversion = 'None'
#if comversion is None, remove it so it doesn't populate with 'None'
if comversion == 'None':
chunk_f_f = re.sub('\$VolumeN', '', mylar.CONFIG.FOLDER_FORMAT)
chunk_f = re.compile(r'\s+')
folderformat = chunk_f.sub(' ', chunk_f_f)
else:
folderformat = mylar.CONFIG.FOLDER_FORMAT
#do work to generate folder path
values = {'$Series': comicname_folder,
'$Publisher': publisher,
'$Year': year,
'$series': comicname_folder.lower(),
'$publisher': publisher.lower(),
'$VolumeY': 'V' + str(year),
'$VolumeN': comversion,
'$Annual': 'Annual',
'$Type': booktype
}
#set the paths here with the seperator removed allowing for cross-platform altering.
ccdir = re.sub(r'[\\|/]', '%&', mylar.CONFIG.NEWCOM_DIR)
ddir = re.sub(r'[\\|/]', '%&', mylar.CONFIG.DESTINATION_DIR)
dlc = re.sub(r'[\\|/]', '%&', dl['ComicLocation'])
if mylar.CONFIG.FFTONEWCOM_DIR:
#if this is enabled (1) it will apply the Folder_Format to all the new dirs
if mylar.CONFIG.FOLDER_FORMAT == '':
comlocation = re.sub(ddir, ccdir, dlc).strip()
else:
first = replace_all(folderformat, values)
if mylar.CONFIG.REPLACE_SPACES:
#mylar.CONFIG.REPLACE_CHAR ...determines what to replace spaces with underscore or dot
first = first.replace(' ', mylar.CONFIG.REPLACE_CHAR)
comlocation = os.path.join(mylar.CONFIG.NEWCOM_DIR, first).strip()
else:
#DESTINATION_DIR = /mnt/mediavg/Comics
#NEWCOM_DIR = /mnt/mediavg/Comics/Comics-1
#dl['ComicLocation'] = /mnt/mediavg/Comics/Batman-(2011)
comlocation = re.sub(ddir, ccdir, dlc).strip()
#regenerate the new path location so that it's os.dependent now.
com_done = re.sub('%&', os.sep.encode('unicode-escape'), comlocation).strip()
comloc.append({"comlocation": com_done,
"origlocation": dl['ComicLocation'],
"comicid": dl['ComicID']})
if len(comloc) > 0:
#give the information about what we're doing.
if mylar.CONFIG.FFTONEWCOM_DIR:
logger.info('FFTONEWCOM_DIR is enabled. Applying the existing folder format to ALL directories regardless of existing location paths')
else:
logger.info('FFTONEWCOM_DIR is not enabled. I will keep existing subdirectory paths, and will only change the actual Comic Location in the path.')
logger.fdebug(' (ie. /mnt/Comics/Marvel/Hush-(2012) to /mnt/mynewLocation/Marvel/Hush-(2012) ')
#do the deed.
for cl in comloc:
ctrlVal = {"ComicID": cl['comicid']}
newVal = {"ComicLocation": cl['comlocation']}
myDB.upsert("Comics", newVal, ctrlVal)
logger.fdebug('Updated : ' + cl['origlocation'] + ' .: TO :. ' + cl['comlocation'])
logger.info('Updated ' + str(len(comloc)) + ' series to a new Comic Location as specified in the config.ini')
else:
logger.fdebug('Failed in updating the Comic Locations. Check Folder Format string and/or log the issue.')
else:
logger.info('There are no series in your watchlist to Update the locations. Not updating anything at this time.')
#set the value to 0 here so we don't keep on doing this...
mylar.CONFIG.LOCMOVE = 0
#mylar.config_write()
else:
logger.info('No new ComicLocation path specified - not updating. Set NEWCOMD_DIR in config.ini')
#raise cherrypy.HTTPRedirect("config")
return
def cleanhtml(raw_html):
#cleanr = re.compile('<.*?>')
#cleantext = re.sub(cleanr, '', raw_html)
#return cleantext
from bs4 import BeautifulSoup
VALID_TAGS = ['div', 'p']
soup = BeautifulSoup(raw_html, "html.parser")
for tag in soup.findAll('p'):
if tag.name not in VALID_TAGS:
tag.replaceWith(tag.renderContents())
flipflop = soup.renderContents()
print flipflop
return flipflop
def issuedigits(issnum):
#import db
int_issnum = None
try:
tst = issnum.isdigit()
except:
try:
isstest = str(issnum)
tst = isstest.isdigit()
except:
return 9999999999
else:
issnum = str(issnum)
if issnum.isdigit():
int_issnum = int(issnum) * 1000
else:
#count = 0
#for char in issnum:
# if char.isalpha():
# count += 1
#if count > 5:
# logger.error('This is not an issue number - not enough numerics to parse')
# int_issnum = 999999999999999
# return int_issnum
try:
if 'au' in issnum.lower() and issnum[:1].isdigit():
int_issnum = (int(issnum[:-2]) * 1000) + ord('a') + ord('u')
elif 'ai' in issnum.lower() and issnum[:1].isdigit():
int_issnum = (int(issnum[:-2]) * 1000) + ord('a') + ord('i')
elif 'inh' in issnum.lower() or 'now' in issnum.lower():
remdec = issnum.find('.') #find the decimal position.
if remdec == -1:
#if no decimal, it's all one string
#remove the last 3 characters from the issue # (INH)
int_issnum = (int(issnum[:-3]) * 1000) + ord('i') + ord('n') + ord('h')
else:
int_issnum = (int(issnum[:-4]) * 1000) + ord('i') + ord('n') + ord('h')
elif 'now' in issnum.lower():
if '!' in issnum: issnum = re.sub('\!', '', issnum)
remdec = issnum.find('.') #find the decimal position.
if remdec == -1:
#if no decimal, it's all one string
#remove the last 3 characters from the issue # (NOW)
int_issnum = (int(issnum[:-3]) * 1000) + ord('n') + ord('o') + ord('w')
else:
int_issnum = (int(issnum[:-4]) * 1000) + ord('n') + ord('o') + ord('w')
elif 'mu' in issnum.lower():
remdec = issnum.find('.')
if remdec == -1:
int_issnum = (int(issnum[:-2]) * 1000) + ord('m') + ord('u')
else:
int_issnum = (int(issnum[:-3]) * 1000) + ord('m') + ord('u')
elif 'hu' in issnum.lower():
remdec = issnum.find('.') #find the decimal position.
if remdec == -1:
int_issnum = (int(issnum[:-2]) * 1000) + ord('h') + ord('u')
else:
int_issnum = (int(issnum[:-3]) * 1000) + ord('h') + ord('u')
except ValueError as e:
logger.error('[' + issnum + '] Unable to properly determine the issue number. Error: %s', e)
return 9999999999
if int_issnum is not None:
return int_issnum
#try:
# issnum.decode('ascii')
# logger.fdebug('ascii character.')
#except:
# logger.fdebug('Unicode character detected: ' + issnum)
#else: issnum.decode(mylar.SYS_ENCODING).decode('utf-8')
if type(issnum) == str:
try:
issnum = issnum.decode('utf-8')
except:
issnum = issnum.decode('windows-1252')
if type(issnum) == unicode:
vals = {u'\xbd':.5,u'\xbc':.25,u'\xbe':.75,u'\u221e':9999999999,u'\xe2':9999999999}
else:
vals = {'\xbd':.5,'\xbc':.25,'\xbe':.75,'\u221e':9999999999,'\xe2':9999999999}
x = [vals[key] for key in vals if key in issnum]
if x:
chk = re.sub('[^0-9]', '', issnum).strip()
if len(chk) == 0:
int_issnum = x[0] * 1000
else:
int_issnum = (int(re.sub('[^0-9]', '', issnum).strip()) + x[0]) * 1000
#logger.fdebug('int_issnum: ' + str(int_issnum))
else:
if any(['.' in issnum, ',' in issnum]):
#logger.fdebug('decimal detected.')
if ',' in issnum: issnum = re.sub(',', '.', issnum)
issst = str(issnum).find('.')
if issst == 0:
issb4dec = 0
else:
issb4dec = str(issnum)[:issst]
decis = str(issnum)[issst +1:]
if len(decis) == 1:
decisval = int(decis) * 10
issaftdec = str(decisval)
elif len(decis) == 2:
decisval = int(decis)
issaftdec = str(decisval)
else:
decisval = decis
issaftdec = str(decisval)
#if there's a trailing decimal (ie. 1.50.) and it's either intentional or not, blow it away.
if issaftdec[-1:] == '.':
issaftdec = issaftdec[:-1]
try:
int_issnum = (int(issb4dec) * 1000) + (int(issaftdec) * 10)
except ValueError:
#logger.fdebug('This has no issue # for me to get - Either a Graphic Novel or one-shot.')
int_issnum = 999999999999999
else:
try:
x = float(issnum)
#logger.info(x)
#validity check
if x < 0:
#logger.info("I've encountered a negative issue #: " + str(issnum) + ". Trying to accomodate.")
int_issnum = (int(x) *1000) - 1
elif bool(x):
logger.fdebug('Infinity issue found.')
int_issnum = 9999999999 * 1000
else: raise ValueError
except ValueError, e:
#this will account for any alpha in a issue#, so long as it doesn't have decimals.
x = 0
tstord = None
issno = None
invchk = "false"
if issnum.lower() != 'preview':
while (x < len(issnum)):
if issnum[x].isalpha():
#take first occurance of alpha in string and carry it through
tstord = issnum[x:].rstrip()
tstord = re.sub('[\-\,\.\+]', '', tstord).rstrip()
issno = issnum[:x].rstrip()
issno = re.sub('[\-\,\.\+]', '', issno).rstrip()
try:
isschk = float(issno)
except ValueError, e:
if len(issnum) == 1 and issnum.isalpha():
break
logger.fdebug('[' + issno + '] Invalid numeric for issue - cannot be found. Ignoring.')
issno = None
tstord = None
invchk = "true"
break
x+=1
if tstord is not None and issno is not None:
a = 0
ordtot = 0
if len(issnum) == 1 and issnum.isalpha():
int_issnum = ord(tstord.lower())
else:
while (a < len(tstord)):
ordtot += ord(tstord[a].lower()) #lower-case the letters for simplicty
a+=1
int_issnum = (int(issno) * 1000) + ordtot
elif invchk == "true":
if any([issnum.lower() == 'fall', issnum.lower() == 'spring', issnum.lower() == 'summer', issnum.lower() == 'winter']):
inu = 0
ordtot = 0
while (inu < len(issnum)):
ordtot += ord(issnum[inu].lower()) #lower-case the letters for simplicty
inu+=1
int_issnum = ordtot
else:
logger.fdebug('this does not have an issue # that I can parse properly.')
return 999999999999999
else:
if issnum == '9-5':
issnum = u'9\xbd'
logger.fdebug('issue: 9-5 is an invalid entry. Correcting to : ' + issnum)
int_issnum = (9 * 1000) + (.5 * 1000)
elif issnum == '112/113':
int_issnum = (112 * 1000) + (.5 * 1000)
elif issnum == '14-16':
int_issnum = (15 * 1000) + (.5 * 1000)
elif issnum.lower() == 'preview':
inu = 0
ordtot = 0
while (inu < len(issnum)):
ordtot += ord(issnum[inu].lower()) #lower-case the letters for simplicty
inu+=1
int_issnum = ordtot
else:
logger.error(issnum + ' this has an alpha-numeric in the issue # which I cannot account for.')
return 999999999999999
return int_issnum
def checkthepub(ComicID):
#import db
myDB = db.DBConnection()
publishers = ['marvel', 'dc', 'darkhorse']
pubchk = myDB.selectone("SELECT * FROM comics WHERE ComicID=?", [ComicID]).fetchone()
if pubchk is None:
logger.fdebug('No publisher information found to aid in determining series..defaulting to base check of 55 days.')
return mylar.CONFIG.BIGGIE_PUB
else:
for publish in publishers:
if publish in pubchk['ComicPublisher'].lower():
#logger.fdebug('Biggie publisher detected - ' + pubchk['ComicPublisher'])
return mylar.CONFIG.BIGGIE_PUB
#logger.fdebug('Indie publisher detected - ' + pubchk['ComicPublisher'])
return mylar.CONFIG.INDIE_PUB
def annual_update():
#import db
myDB = db.DBConnection()
annuallist = myDB.select('SELECT * FROM annuals')
if annuallist is None:
logger.info('no annuals to update.')
return
cnames = []
#populate the ComicName field with the corresponding series name from the comics table.
for ann in annuallist:
coms = myDB.selectone('SELECT * FROM comics WHERE ComicID=?', [ann['ComicID']]).fetchone()
cnames.append({'ComicID': ann['ComicID'],
'ComicName': coms['ComicName']
})
#write in a seperate loop to avoid db locks
i=0
for cns in cnames:
ctrlVal = {"ComicID": cns['ComicID']}
newVal = {"ComicName": cns['ComicName']}
myDB.upsert("annuals", newVal, ctrlVal)
i+=1
logger.info(str(i) + ' series have been updated in the annuals table.')
return
def replacetheslash(data):
# this is necessary for the cache directory to display properly in IE/FF.
# os.path.join will pipe in the '\' in windows, which won't resolve
# when viewing through cherrypy - so convert it and viola.
if platform.system() == "Windows":
slashreplaced = data.replace('\\', '/')
else:
slashreplaced = data
return slashreplaced
def urlretrieve(urlfile, fpath):
chunk = 4096
f = open(fpath, "w")
while 1:
data = urlfile.read(chunk)
if not data:
print "done."
break
f.write(data)
print "Read %s bytes"%len(data)
def renamefile_readingorder(readorder):
logger.fdebug('readingorder#: ' + str(readorder))
if int(readorder) < 10: readord = "00" + str(readorder)
elif int(readorder) >= 10 and int(readorder) < 99: readord = "0" + str(readorder)
else: readord = str(readorder)
return readord
def latestdate_fix():
#import db
datefix = []
cnupdate = []
myDB = db.DBConnection()
comiclist = myDB.select('SELECT * FROM comics')
if comiclist is None:
logger.fdebug('No Series in watchlist to correct latest date')
return
for cl in comiclist:
if cl['ComicName_Filesafe'] is None:
cnupdate.append({"comicid": cl['ComicID'],
"comicname_filesafe": filesafe(cl['ComicName'])})
latestdate = cl['LatestDate']
#logger.fdebug("latestdate: " + str(latestdate))
try:
if latestdate[8:] == '':
#logger.fdebug("invalid date " + str(latestdate) + " appending 01 for day to avoid errors")
if len(latestdate) <= 7:
finddash = latestdate.find('-')
#logger.info('dash found at position ' + str(finddash))
if finddash != 4: #format of mm-yyyy
lat_month = latestdate[:finddash]
lat_year = latestdate[finddash +1:]
else: #format of yyyy-mm
lat_month = latestdate[finddash +1:]
lat_year = latestdate[:finddash]
latestdate = (lat_year) + '-' + str(lat_month) + '-01'
datefix.append({"comicid": cl['ComicID'],
"latestdate": latestdate})
#logger.info('latest date: ' + str(latestdate))
except:
datefix.append({"comicid": cl['ComicID'],
"latestdate": '0000-00-00'})
#now we fix.
if len(datefix) > 0:
logger.info('Preparing to correct/fix ' + str(len(datefix)) + ' series that have incorrect values given for the Latest Date field.')
for df in datefix:
newCtrl = {"ComicID": df['comicid']}
newVal = {"LatestDate": df['latestdate']}
myDB.upsert("comics", newVal, newCtrl)
if len(cnupdate) > 0:
logger.info('Preparing to update ' + str(len(cnupdate)) + ' series on your watchlist for use with non-ascii characters')
for cn in cnupdate:
newCtrl = {"ComicID": cn['comicid']}
newVal = {"ComicName_Filesafe": cn['comicname_filesafe']}
myDB.upsert("comics", newVal, newCtrl)
return
def upgrade_dynamic():
#import db
dynamic_comiclist = []
myDB = db.DBConnection()
#update the comicdb to include the Dynamic Names (and any futher changes as required)
clist = myDB.select('SELECT * FROM Comics')
for cl in clist:
cl_d = mylar.filechecker.FileChecker(watchcomic=cl['ComicName'])
cl_dyninfo = cl_d.dynamic_replace(cl['ComicName'])
dynamic_comiclist.append({'DynamicComicName': re.sub('[\|\s]','', cl_dyninfo['mod_seriesname'].lower()).strip(),
'ComicID': cl['ComicID']})
if len(dynamic_comiclist) > 0:
for dl in dynamic_comiclist:
CtrlVal = {"ComicID": dl['ComicID']}
newVal = {"DynamicComicName": dl['DynamicComicName']}
myDB.upsert("Comics", newVal, CtrlVal)
#update the storyarcsdb to include the Dynamic Names (and any futher changes as required)
dynamic_storylist = []
rlist = myDB.select('SELECT * FROM storyarcs WHERE StoryArcID is not NULL')
for rl in rlist:
rl_d = mylar.filechecker.FileChecker(watchcomic=rl['ComicName'])
rl_dyninfo = cl_d.dynamic_replace(rl['ComicName'])
dynamic_storylist.append({'DynamicComicName': re.sub('[\|\s]','', rl_dyninfo['mod_seriesname'].lower()).strip(),
'IssueArcID': rl['IssueArcID']})
if len(dynamic_storylist) > 0:
for ds in dynamic_storylist:
CtrlVal = {"IssueArcID": ds['IssueArcID']}
newVal = {"DynamicComicName": ds['DynamicComicName']}
myDB.upsert("storyarcs", newVal, CtrlVal)
logger.info('Finished updating ' + str(len(dynamic_comiclist)) + ' / ' + str(len(dynamic_storylist)) + ' entries within the db.')
mylar.CONFIG.DYNAMIC_UPDATE = 4
mylar.CONFIG.writeconfig()
return
def checkFolder(folderpath=None):
from mylar import PostProcessor
queue = Queue.Queue()
#monitor a selected folder for 'snatched' files that haven't been processed
if folderpath is None:
logger.info('Checking folder ' + mylar.CONFIG.CHECK_FOLDER + ' for newly snatched downloads')
path = mylar.CONFIG.CHECK_FOLDER
else:
logger.info('Submitted folder ' + folderpath + ' for direct folder post-processing')
path = folderpath
PostProcess = PostProcessor.PostProcessor('Manual Run', path, queue=queue)
vals = PostProcess.Process()
return
def LoadAlternateSearchNames(seriesname_alt, comicid):
#seriesname_alt = db.comics['AlternateSearch']
AS_Alt = []
Alternate_Names = {}
alt_count = 0
#logger.fdebug('seriesname_alt:' + str(seriesname_alt))
if seriesname_alt is None or seriesname_alt == 'None':
return "no results"
else:
chkthealt = seriesname_alt.split('##')
if chkthealt == 0:
AS_Alternate = seriesname_alt
AS_Alt.append(seriesname_alt)
for calt in chkthealt:
AS_Alter = re.sub('##', '', calt)
u_altsearchcomic = AS_Alter.encode('ascii', 'ignore').strip()
AS_formatrem_seriesname = re.sub('\s+', ' ', u_altsearchcomic)
if AS_formatrem_seriesname[:1] == ' ': AS_formatrem_seriesname = AS_formatrem_seriesname[1:]
AS_Alt.append({"AlternateName": AS_formatrem_seriesname})
alt_count+=1
Alternate_Names['AlternateName'] = AS_Alt
Alternate_Names['ComicID'] = comicid
Alternate_Names['Count'] = alt_count
logger.info('AlternateNames returned:' + str(Alternate_Names))
return Alternate_Names
def havetotals(refreshit=None):
#import db
comics = []
myDB = db.DBConnection()
if refreshit is None:
if mylar.CONFIG.ANNUALS_ON:
comiclist = myDB.select('SELECT comics.*, COUNT(totalAnnuals.IssueID) AS TotalAnnuals FROM comics LEFT JOIN annuals as totalAnnuals on totalAnnuals.ComicID = comics.ComicID GROUP BY comics.ComicID order by comics.ComicSortName COLLATE NOCASE')
else:
comiclist = myDB.select('SELECT * FROM comics GROUP BY ComicID order by ComicSortName COLLATE NOCASE')
else:
comiclist = []
comicref = myDB.selectone('SELECT comics.ComicID AS ComicID, comics.Have AS Have, comics.Total as Total, COUNT(totalAnnuals.IssueID) AS TotalAnnuals FROM comics LEFT JOIN annuals as totalAnnuals on totalAnnuals.ComicID = comics.ComicID WHERE comics.ComicID=? GROUP BY comics.ComicID', [refreshit]).fetchone()
#refreshit is the ComicID passed from the Refresh Series to force/check numerical have totals
comiclist.append({"ComicID": comicref['ComicID'],
"Have": comicref['Have'],
"Total": comicref['Total'],
"TotalAnnuals": comicref['TotalAnnuals']})
for comic in comiclist:
#--not sure about this part
#if comic['Total'] is None:
# if refreshit is not None:
# logger.fdebug(str(comic['ComicID']) + ' has no issuedata available. Forcing complete Refresh/Rescan')
# return True
# else:
# continue
try:
totalissues = comic['Total']
# if mylar.CONFIG.ANNUALS_ON:
# totalissues += comic['TotalAnnuals']
haveissues = comic['Have']
except TypeError:
logger.warning('[Warning] ComicID: ' + str(comic['ComicID']) + ' is incomplete - Removing from DB. You should try to re-add the series.')
myDB.action("DELETE from COMICS WHERE ComicID=? AND ComicName LIKE 'Comic ID%'", [comic['ComicID']])
myDB.action("DELETE from ISSUES WHERE ComicID=? AND ComicName LIKE 'Comic ID%'", [comic['ComicID']])
continue
if not haveissues:
havetracks = 0
if refreshit is not None:
if haveissues > totalissues:
return True # if it's 5/4, send back to updater and don't restore previous status'
else:
return False # if it's 5/5 or 4/5, send back to updater and restore previous status'
try:
percent = (haveissues *100.0) /totalissues
if percent > 100:
percent = 101
except (ZeroDivisionError, TypeError):
percent = 0
totalissues = '?'
if comic['LatestDate'] is None:
logger.warn(comic['ComicName'] + ' has not finished loading. Nulling some values so things display properly until they can populate.')
recentstatus = 'Loading'
elif comic['ComicPublished'] is None or comic['ComicPublished'] == '' or comic['LatestDate'] is None:
recentstatus = 'Unknown'
elif comic['ForceContinuing'] == 1:
recentstatus = 'Continuing'
elif 'present' in comic['ComicPublished'].lower() or (today()[:4] in comic['LatestDate']):
latestdate = comic['LatestDate']
#pull-list f'd up the date by putting '15' instead of '2015' causing 500 server errors
if '-' in latestdate[:3]:
st_date = latestdate.find('-')
st_remainder = latestdate[st_date+1:]
st_year = latestdate[:st_date]
year = '20' + st_year
latestdate = str(year) + '-' + str(st_remainder)
#logger.fdebug('year set to: ' + latestdate)
c_date = datetime.date(int(latestdate[:4]), int(latestdate[5:7]), 1)
n_date = datetime.date.today()
recentchk = (n_date - c_date).days
if comic['NewPublish'] is True:
recentstatus = 'Continuing'
else:
#do this just incase and as an extra measure of accuracy hopefully.
if recentchk < 55:
recentstatus = 'Continuing'
else:
recentstatus = 'Ended'
else:
recentstatus = 'Ended'
if recentstatus == 'Loading':
cpub = comic['ComicPublished']
else:
try:
cpub = re.sub('(N)', '', comic['ComicPublished']).strip()
except Exception as e:
logger.warn('[Error: %s] No Publisher found for %s - you probably want to Refresh the series when you get a chance.' % (e, comic['ComicName']))
cpub = None
comics.append({"ComicID": comic['ComicID'],
"ComicName": comic['ComicName'],
"ComicSortName": comic['ComicSortName'],
"ComicPublisher": comic['ComicPublisher'],
"ComicYear": comic['ComicYear'],
"ComicImage": comic['ComicImage'],
"LatestIssue": comic['LatestIssue'],
"LatestDate": comic['LatestDate'],
"ComicPublished": cpub,
"Status": comic['Status'],
"recentstatus": recentstatus,
"percent": percent,
"totalissues": totalissues,
"haveissues": haveissues,
"DateAdded": comic['LastUpdated'],
"Type": comic['Type'],
"Corrected_Type": comic['Corrected_Type']})
return comics
def filesafe(comic):
import unicodedata
if u'\u2014' in comic:
comic = re.sub(u'\u2014', ' - ', comic)
try:
u_comic = unicodedata.normalize('NFKD', comic).encode('ASCII', 'ignore').strip()
except TypeError:
u_comic = comic.encode('ASCII', 'ignore').strip()
comicname_filesafe = re.sub('[\:\'\"\,\?\!\\\]', '', u_comic)
comicname_filesafe = re.sub('[\/\*]', '-', comicname_filesafe)
return comicname_filesafe
def IssueDetails(filelocation, IssueID=None, justinfo=False):
import zipfile
from xml.dom.minidom import parseString
issuedetails = []
issuetag = None
if justinfo is False:
dstlocation = os.path.join(mylar.CONFIG.CACHE_DIR, 'temp.zip')
if filelocation.endswith('.cbz'):
logger.fdebug('CBZ file detected. Checking for .xml within file')
shutil.copy(filelocation, dstlocation)
else:
logger.fdebug('filename is not a cbz : ' + filelocation)
return
cover = "notfound"
pic_extensions = ('.jpg','.png','.webp')
modtime = os.path.getmtime(dstlocation)
low_infile = 999999
try:
with zipfile.ZipFile(dstlocation, 'r') as inzipfile:
for infile in sorted(inzipfile.namelist()):
tmp_infile = re.sub("[^0-9]","", infile).strip()
if tmp_infile == '':
pass
elif int(tmp_infile) < int(low_infile):
low_infile = tmp_infile
low_infile_name = infile
if infile == 'ComicInfo.xml':
logger.fdebug('Extracting ComicInfo.xml to display.')
dst = os.path.join(mylar.CONFIG.CACHE_DIR, 'ComicInfo.xml')
data = inzipfile.read(infile)
#print str(data)
issuetag = 'xml'
#looks for the first page and assumes it's the cover. (Alternate covers handled later on)
elif any(['000.' in infile, '00.' in infile]) and infile.endswith(pic_extensions) and cover == "notfound":
logger.fdebug('Extracting primary image ' + infile + ' as coverfile for display.')
local_file = open(os.path.join(mylar.CONFIG.CACHE_DIR, 'temp.jpg'), "wb")
local_file.write(inzipfile.read(infile))
local_file.close
cover = "found"
elif any(['00a' in infile, '00b' in infile, '00c' in infile, '00d' in infile, '00e' in infile]) and infile.endswith(pic_extensions) and cover == "notfound":
logger.fdebug('Found Alternate cover - ' + infile + ' . Extracting.')
altlist = ('00a', '00b', '00c', '00d', '00e')
for alt in altlist:
if alt in infile:
local_file = open(os.path.join(mylar.CONFIG.CACHE_DIR, 'temp.jpg'), "wb")
local_file.write(inzipfile.read(infile))
local_file.close
cover = "found"
break
elif (any(['001.jpg' in infile, '001.png' in infile, '001.webp' in infile, '01.jpg' in infile, '01.png' in infile, '01.webp' in infile]) or all(['0001' in infile, infile.endswith(pic_extensions)]) or all(['01' in infile, infile.endswith(pic_extensions)])) and cover == "notfound":
logger.fdebug('Extracting primary image ' + infile + ' as coverfile for display.')
local_file = open(os.path.join(mylar.CONFIG.CACHE_DIR, 'temp.jpg'), "wb")
local_file.write(inzipfile.read(infile))
local_file.close
cover = "found"
if cover != "found":
logger.fdebug('Invalid naming sequence for jpgs discovered. Attempting to find the lowest sequence and will use as cover (it might not work). Currently : ' + str(low_infile))
local_file = open(os.path.join(mylar.CONFIG.CACHE_DIR, 'temp.jpg'), "wb")
logger.fdebug('infile_name used for displaying: %s' % low_infile_name)
local_file.write(inzipfile.read(low_infile_name))
local_file.close
cover = "found"
except:
logger.info('ERROR. Unable to properly retrieve the cover for displaying. It\'s probably best to re-tag this file.')
return
ComicImage = os.path.join('cache', 'temp.jpg?' +str(modtime))
IssueImage = replacetheslash(ComicImage)
else:
IssueImage = "None"
try:
with zipfile.ZipFile(filelocation, 'r') as inzipfile:
for infile in sorted(inzipfile.namelist()):
if infile == 'ComicInfo.xml':
logger.fdebug('Found ComicInfo.xml - now retrieving information.')
data = inzipfile.read(infile)
issuetag = 'xml'
break
except:
logger.info('ERROR. Unable to properly retrieve the cover for displaying. It\'s probably best to re-tag this file.')
return
if issuetag is None:
data = None
try:
dz = zipfile.ZipFile(filelocation, 'r')
data = dz.comment
except:
logger.warn('Unable to extract comment field from zipfile.')
return
else:
if data:
issuetag = 'comment'
else:
logger.warn('No metadata available in zipfile comment field.')
return
logger.info('Tag returned as being: ' + str(issuetag))
#logger.info('data:' + str(data))
if issuetag == 'xml':
#import easy to use xml parser called minidom:
dom = parseString(data)
results = dom.getElementsByTagName('ComicInfo')
for result in results:
try:
issue_title = result.getElementsByTagName('Title')[0].firstChild.wholeText
except:
issue_title = "None"
try:
series_title = result.getElementsByTagName('Series')[0].firstChild.wholeText
except:
series_title = "None"
try:
series_volume = result.getElementsByTagName('Volume')[0].firstChild.wholeText
except:
series_volume = "None"
try:
issue_number = result.getElementsByTagName('Number')[0].firstChild.wholeText
except:
issue_number = "None"
try:
summary = result.getElementsByTagName('Summary')[0].firstChild.wholeText
except:
summary = "None"
if '*List' in summary:
summary_cut = summary.find('*List')
summary = summary[:summary_cut]
#check here to see if Covers exist as they will probably be misnamed when trying to determine the actual cover
# (ie. 00a.jpg / 00d.jpg - when there's a Cover A or a Cover D listed)
try:
notes = result.getElementsByTagName('Notes')[0].firstChild.wholeText #IssueID is in here
except:
notes = "None"
try:
year = result.getElementsByTagName('Year')[0].firstChild.wholeText
except:
year = "None"
try:
month = result.getElementsByTagName('Month')[0].firstChild.wholeText
except:
month = "None"
try:
day = result.getElementsByTagName('Day')[0].firstChild.wholeText
except:
day = "None"
try:
writer = result.getElementsByTagName('Writer')[0].firstChild.wholeText
except:
writer = "None"
try:
penciller = result.getElementsByTagName('Penciller')[0].firstChild.wholeText
except:
penciller = "None"
try:
inker = result.getElementsByTagName('Inker')[0].firstChild.wholeText
except:
inker = "None"
try:
colorist = result.getElementsByTagName('Colorist')[0].firstChild.wholeText
except:
colorist = "None"
try:
letterer = result.getElementsByTagName('Letterer')[0].firstChild.wholeText
except:
letterer = "None"
try:
cover_artist = result.getElementsByTagName('CoverArtist')[0].firstChild.wholeText
except:
cover_artist = "None"
try:
editor = result.getElementsByTagName('Editor')[0].firstChild.wholeText
except:
editor = "None"
try:
publisher = result.getElementsByTagName('Publisher')[0].firstChild.wholeText
except:
publisher = "None"
try:
webpage = result.getElementsByTagName('Web')[0].firstChild.wholeText
except:
webpage = "None"
try:
pagecount = result.getElementsByTagName('PageCount')[0].firstChild.wholeText
except:
pagecount = 0
#not used atm.
#to validate a front cover if it's tagged as one within the zip (some do this)
#i = 0
#try:
# pageinfo = result.getElementsByTagName('Page')[0].attributes
# if pageinfo: pageinfo_test == True
#except:
# pageinfo_test = False
#if pageinfo_test:
# while (i < int(pagecount)):
# pageinfo = result.getElementsByTagName('Page')[i].attributes
# attrib = pageinfo.getNamedItem('Image')
# #logger.fdebug('Frontcover validated as being image #: ' + str(attrib.value))
# att = pageinfo.getNamedItem('Type')
# #logger.fdebug('pageinfo: ' + str(pageinfo))
# if att.value == 'FrontCover':
# #logger.fdebug('FrontCover detected. Extracting.')
# break
# i+=1
elif issuetag == 'comment':
logger.info('CBL Tagging.')
stripline = 'Archive: ' + filelocation
data = re.sub(stripline, '', data.encode("utf-8")).strip()
if data is None or data == '':
return
import ast
ast_data = ast.literal_eval(str(data))
lastmodified = ast_data['lastModified']
dt = ast_data['ComicBookInfo/1.0']
try:
publisher = dt['publisher']
except:
publisher = None
try:
year = dt['publicationYear']
except:
year = None
try:
month = dt['publicationMonth']
except:
month = None
try:
day = dt['publicationDay']
except:
day = None
try:
issue_title = dt['title']
except:
issue_title = None
try:
series_title = dt['series']
except:
series_title = None
try:
issue_number = dt['issue']
except:
issue_number = None
try:
summary = dt['comments']
except:
summary = "None"
editor = "None"
colorist = "None"
artist = "None"
writer = "None"
letterer = "None"
cover_artist = "None"
penciller = "None"
inker = "None"
try:
series_volume = dt['volume']
except:
series_volume = None
try:
t = dt['credits']
except:
editor = None
colorist = None
artist = None
writer = None
letterer = None
cover_artist = None
penciller = None
inker = None
else:
for cl in dt['credits']:
if cl['role'] == 'Editor':
if editor == "None": editor = cl['person']
else: editor += ', ' + cl['person']
elif cl['role'] == 'Colorist':
if colorist == "None": colorist = cl['person']
else: colorist += ', ' + cl['person']
elif cl['role'] == 'Artist':
if artist == "None": artist = cl['person']
else: artist += ', ' + cl['person']
elif cl['role'] == 'Writer':
if writer == "None": writer = cl['person']
else: writer += ', ' + cl['person']
elif cl['role'] == 'Letterer':
if letterer == "None": letterer = cl['person']
else: letterer += ', ' + cl['person']
elif cl['role'] == 'Cover':
if cover_artist == "None": cover_artist = cl['person']
else: cover_artist += ', ' + cl['person']
elif cl['role'] == 'Penciller':
if penciller == "None": penciller = cl['person']
else: penciller += ', ' + cl['person']
elif cl['role'] == 'Inker':
if inker == "None": inker = cl['person']
else: inker += ', ' + cl['person']
try:
notes = dt['notes']
except:
notes = "None"
try:
webpage = dt['web']
except:
webpage = "None"
try:
pagecount = dt['pagecount']
except:
pagecount = "None"
else:
logger.warn('Unable to locate any metadata within cbz file. Tag this file and try again if necessary.')
return
issuedetails.append({"title": issue_title,
"series": series_title,
"volume": series_volume,
"issue_number": issue_number,
"summary": summary,
"notes": notes,
"year": year,
"month": month,
"day": day,
"writer": writer,
"penciller": penciller,
"inker": inker,
"colorist": colorist,
"letterer": letterer,
"cover_artist": cover_artist,
"editor": editor,
"publisher": publisher,
"webpage": webpage,
"pagecount": pagecount,
"IssueImage": IssueImage})
return issuedetails
def get_issue_title(IssueID=None, ComicID=None, IssueNumber=None, IssueArcID=None):
#import db
myDB = db.DBConnection()
if IssueID:
issue = myDB.selectone('SELECT * FROM issues WHERE IssueID=?', [IssueID]).fetchone()
if issue is None:
issue = myDB.selectone('SELECT * FROM annuals WHERE IssueID=?', [IssueID]).fetchone()
if issue is None:
logger.fdebug('Unable to locate given IssueID within the db. Assuming Issue Title is None.')
return None
else:
issue = myDB.selectone('SELECT * FROM issues WHERE ComicID=? AND Int_IssueNumber=?', [ComicID, issuedigits(IssueNumber)]).fetchone()
if issue is None:
issue = myDB.selectone('SELECT * FROM annuals WHERE IssueID=?', [IssueID]).fetchone()
if issue is None:
if IssueArcID:
issue = myDB.selectone('SELECT * FROM readlist WHERE IssueArcID=?', [IssueArcID]).fetchone()
if issue is None:
logger.fdebug('Unable to locate given IssueID within the db. Assuming Issue Title is None.')
return None
else:
logger.fdebug('Unable to locate given IssueID within the db. Assuming Issue Title is None.')
return None
return issue['IssueName']
def int_num(s):
try:
return int(s)
except ValueError:
return float(s)
def listPull(weeknumber, year):
#import db
library = {}
myDB = db.DBConnection()
# Get individual comics
list = myDB.select("SELECT ComicID FROM Weekly WHERE weeknumber=? AND year=?", [weeknumber,year])
for row in list:
library[row['ComicID']] = row['ComicID']
return library
def listLibrary(comicid=None):
#import db
library = {}
myDB = db.DBConnection()
if comicid is None:
if mylar.CONFIG.ANNUALS_ON is True:
list = myDB.select("SELECT a.comicid, b.releasecomicid, a.status FROM Comics AS a LEFT JOIN annuals AS b on a.comicid=b.comicid group by a.comicid")
else:
list = myDB.select("SELECT comicid, status FROM Comics group by comicid")
else:
if mylar.CONFIG.ANNUALS_ON is True:
list = myDB.select("SELECT a.comicid, b.releasecomicid, a.status FROM Comics AS a LEFT JOIN annuals AS b on a.comicid=b.comicid WHERE a.comicid=? group by a.comicid", [re.sub('4050-', '', comicid).strip()])
else:
list = myDB.select("SELECT comicid, status FROM Comics WHERE comicid=? group by comicid", [re.sub('4050-', '', comicid).strip()])
for row in list:
library[row['ComicID']] = {'comicid': row['ComicID'],
'status': row['Status']}
try:
if row['ReleaseComicID'] is not None:
library[row['ReleaseComicID']] = {'comicid': row['ComicID'],
'status': row['Status']}
except:
pass
return library
def listStoryArcs():
#import db
library = {}
myDB = db.DBConnection()
# Get Distinct Arc IDs
#list = myDB.select("SELECT DISTINCT(StoryArcID) FROM storyarcs");
#for row in list:
# library[row['StoryArcID']] = row['StoryArcID']
# Get Distinct CV Arc IDs
list = myDB.select("SELECT DISTINCT(CV_ArcID) FROM storyarcs");
for row in list:
library[row['CV_ArcID']] = {'comicid': row['CV_ArcID']}
return library
def listoneoffs(weeknumber, year):
#import db
library = []
myDB = db.DBConnection()
# Get Distinct one-off issues from the pullist that have already been downloaded / snatched
list = myDB.select("SELECT DISTINCT(IssueID), Status, ComicID, ComicName, Status, IssueNumber FROM oneoffhistory WHERE weeknumber=? and year=? AND Status='Downloaded' OR Status='Snatched'", [weeknumber, year])
for row in list:
library.append({'IssueID': row['IssueID'],
'ComicID': row['ComicID'],
'ComicName': row['ComicName'],
'IssueNumber': row['IssueNumber'],
'Status': row['Status'],
'weeknumber': weeknumber,
'year': year})
return library
def manualArc(issueid, reading_order, storyarcid):
#import db
if issueid.startswith('4000-'):
issueid = issueid[5:]
myDB = db.DBConnection()
arc_chk = myDB.select("SELECT * FROM storyarcs WHERE StoryArcID=? AND NOT Manual is 'deleted'", [storyarcid])
storyarcname = arc_chk[0]['StoryArc']
storyarcissues = arc_chk[0]['TotalIssues']
iss_arcids = []
for issarc in arc_chk:
iss_arcids.append({"IssueArcID": issarc['IssueArcID'],
"IssueID": issarc['IssueID'],
"Manual": issarc['Manual'],
"ReadingOrder": issarc['ReadingOrder']})
arc_results = mylar.cv.getComic(comicid=None, type='issue', issueid=None, arcid=storyarcid, arclist='M' + str(issueid))
arcval = arc_results['issuechoice'][0]
comicname = arcval['ComicName']
st_d = mylar.filechecker.FileChecker(watchcomic=comicname)
st_dyninfo = st_d.dynamic_replace(comicname)
dynamic_name = re.sub('[\|\s]','', st_dyninfo['mod_seriesname'].lower()).strip()
issname = arcval['Issue_Name']
issid = str(arcval['IssueID'])
comicid = str(arcval['ComicID'])
cidlist = str(comicid)
st_issueid = None
manual_mod = 'added'
new_readorder = []
for aid in iss_arcids:
if aid['IssueID'] == issid:
logger.info('Issue already exists for storyarc [IssueArcID:' + aid['IssueArcID'] + '][Manual:' + aid['Manual'])
st_issueid = aid['IssueArcID']
manual_mod = aid['Manual']
if reading_order is None:
#if no reading order is given, drop in the last spot.
reading_order = len(iss_arcids) + 1
if int(aid['ReadingOrder']) >= int(reading_order):
reading_seq = int(aid['ReadingOrder']) + 1
else:
reading_seq = int(aid['ReadingOrder'])
new_readorder.append({'IssueArcID': aid['IssueArcID'],
'IssueID': aid['IssueID'],
'ReadingOrder': reading_seq})
import random
if st_issueid is None:
st_issueid = str(storyarcid) + "_" + str(random.randint(1000,9999))
issnum = arcval['Issue_Number']
issdate = str(arcval['Issue_Date'])
storedate = str(arcval['Store_Date'])
int_issnum = issuedigits(issnum)
comicid_results = mylar.cv.getComic(comicid=None, type='comicyears', comicidlist=cidlist)
seriesYear = 'None'
issuePublisher = 'None'
seriesVolume = 'None'
if issname is None:
IssueName = 'None'
else:
IssueName = issname[:70]
for cid in comicid_results:
if cid['ComicID'] == comicid:
seriesYear = cid['SeriesYear']
issuePublisher = cid['Publisher']
seriesVolume = cid['Volume']
#assume that the arc is the same
storyarcpublisher = issuePublisher
break
newCtrl = {"IssueID": issid,
"StoryArcID": storyarcid}
newVals = {"ComicID": comicid,
"IssueArcID": st_issueid,
"StoryArc": storyarcname,
"ComicName": comicname,
"Volume": seriesVolume,
"DynamicComicName": dynamic_name,
"IssueName": IssueName,
"IssueNumber": issnum,
"Publisher": storyarcpublisher,
"TotalIssues": str(int(storyarcissues) +1),
"ReadingOrder": int(reading_order), #arbitrarily set it to the last reading order sequence # just to see if it works.
"IssueDate": issdate,
"ReleaseDate": storedate,
"SeriesYear": seriesYear,
"IssuePublisher": issuePublisher,
"CV_ArcID": storyarcid,
"Int_IssueNumber": int_issnum,
"Manual": manual_mod}
myDB.upsert("storyarcs", newVals, newCtrl)
#now we resequence the reading-order to accomdate the change.
logger.info('Adding the new issue into the reading order & resequencing the order to make sure there are no sequence drops...')
new_readorder.append({'IssueArcID': st_issueid,
'IssueID': issid,
'ReadingOrder': int(reading_order)})
newrl = 0
for rl in sorted(new_readorder, key=itemgetter('ReadingOrder'), reverse=False):
if rl['ReadingOrder'] - 1 != newrl:
rorder = newrl + 1
logger.fdebug(rl['IssueID'] + ' - changing reading order seq to : ' + str(rorder))
else:
rorder = rl['ReadingOrder']
logger.fdebug(rl['IssueID'] + ' - setting reading order seq to : ' + str(rorder))
rl_ctrl = {"IssueID": rl['IssueID'],
"IssueArcID": rl['IssueArcID'],
"StoryArcID": storyarcid}
r1_new = {"ReadingOrder": rorder}
newrl = rorder
myDB.upsert("storyarcs", r1_new, rl_ctrl)
#check to see if the issue exists already so we can set the status right away.
iss_chk = myDB.selectone('SELECT * FROM issues where issueid = ?', [issueid]).fetchone()
if iss_chk is None:
logger.info('Issue is not currently in your watchlist. Setting status to Skipped')
status_change = 'Skipped'
else:
status_change = iss_chk['Status']
logger.info('Issue currently exists in your watchlist. Setting status to ' + status_change)
myDB.upsert("storyarcs", {'Status': status_change}, newCtrl)
return
def listIssues(weeknumber, year):
#import db
library = []
myDB = db.DBConnection()
# Get individual issues
list = myDB.select("SELECT issues.Status, issues.ComicID, issues.IssueID, issues.ComicName, issues.IssueDate, issues.ReleaseDate, weekly.publisher, issues.Issue_Number from weekly, issues where weekly.IssueID = issues.IssueID and weeknumber = ? and year = ?", [int(weeknumber), year])
for row in list:
if row['ReleaseDate'] is None:
tmpdate = row['IssueDate']
else:
tmpdate = row['ReleaseDate']
library.append({'ComicID': row['ComicID'],
'Status': row['Status'],
'IssueID': row['IssueID'],
'ComicName': row['ComicName'],
'Publisher': row['publisher'],
'Issue_Number': row['Issue_Number'],
'IssueYear': tmpdate})
# Add the annuals
if mylar.CONFIG.ANNUALS_ON:
list = myDB.select("SELECT annuals.Status, annuals.ComicID, annuals.ReleaseComicID, annuals.IssueID, annuals.ComicName, annuals.ReleaseDate, annuals.IssueDate, weekly.publisher, annuals.Issue_Number from weekly, annuals where weekly.IssueID = annuals.IssueID and weeknumber = ? and year = ?", [int(weeknumber), year])
for row in list:
if row['ReleaseDate'] is None:
tmpdate = row['IssueDate']
else:
tmpdate = row['ReleaseDate']
library.append({'ComicID': row['ComicID'],
'Status': row['Status'],
'IssueID': row['IssueID'],
'ComicName': row['ComicName'],
'Publisher': row['publisher'],
'Issue_Number': row['Issue_Number'],
'IssueYear': tmpdate})
#tmplist = library
#librarylist = []
#for liblist in tmplist:
# lb = myDB.select('SELECT ComicVersion, Type, ComicYear, ComicID from comics WHERE ComicID=?', [liblist['ComicID']])
# librarylist.append(liblist)
# librarylist.update({'Comic_Volume': lb['ComicVersion'],
# 'ComicYear': lb['ComicYear'],
# 'ComicType': lb['Type']})
return library
def incr_snatched(ComicID):
#import db
myDB = db.DBConnection()
incr_count = myDB.selectone("SELECT Have FROM Comics WHERE ComicID=?", [ComicID]).fetchone()
logger.fdebug('Incrementing HAVE count total to : ' + str(incr_count['Have'] + 1))
newCtrl = {"ComicID": ComicID}
newVal = {"Have": incr_count['Have'] + 1}
myDB.upsert("comics", newVal, newCtrl)
return
def duplicate_filecheck(filename, ComicID=None, IssueID=None, StoryArcID=None, rtnval=None):
#filename = the filename in question that's being checked against
#comicid = the comicid of the series that's being checked for duplication
#issueid = the issueid of the issue that's being checked for duplication
#storyarcid = the storyarcid of the issue that's being checked for duplication.
#rtnval = the return value of a previous duplicate_filecheck that's re-running against new values
#
#import db
myDB = db.DBConnection()
logger.info('[DUPECHECK] Duplicate check for ' + filename)
try:
filesz = os.path.getsize(filename)
except OSError as e:
logger.warn('[DUPECHECK] File cannot be located in location specified. Something has moved or altered the name.')
logger.warn('[DUPECHECK] Make sure if you are using ComicRN, you do not have Completed Download Handling enabled (or vice-versa). Aborting')
return
if IssueID:
dupchk = myDB.selectone("SELECT * FROM issues WHERE IssueID=?", [IssueID]).fetchone()
if dupchk is None:
dupchk = myDB.selectone("SELECT * FROM annuals WHERE IssueID=?", [IssueID]).fetchone()
if dupchk is None:
logger.info('[DUPECHECK] Unable to find corresponding Issue within the DB. Do you still have the series on your watchlist?')
return
series = myDB.selectone("SELECT * FROM comics WHERE ComicID=?", [dupchk['ComicID']]).fetchone()
#if it's a retry and the file was already snatched, the status is Snatched and won't hit the dupecheck.
#rtnval will be one of 3:
#'write' - write new file
#'dupe_file' - do not write new file as existing file is better quality
#'dupe_src' - write new file, as existing file is a lesser quality (dupe)
if dupchk['Status'] == 'Downloaded' or dupchk['Status'] == 'Archived':
try:
dupsize = dupchk['ComicSize']
except:
logger.info('[DUPECHECK] Duplication detection returned no hits as this is a new Snatch. This is not a duplicate.')
rtnval = {'action': "write"}
logger.info('[DUPECHECK] Existing Status already set to ' + dupchk['Status'])
cid = []
if dupsize is None:
logger.info('[DUPECHECK] Existing filesize is 0 bytes as I cannot locate the orginal entry - it is probably archived.')
logger.fdebug('[DUPECHECK] Checking series for unrefreshed series syndrome (USS).')
havechk = myDB.selectone('SELECT * FROM comics WHERE ComicID=?', [ComicID]).fetchone()
if havechk:
if havechk['Have'] > havechk['Total']:
logger.info('[DUPECHECK] Series has invalid issue totals [' + str(havechk['Have']) + '/' + str(havechk['Total']) + '] Attempting to Refresh & continue post-processing this issue.')
cid.append(ComicID)
logger.fdebug('[DUPECHECK] ComicID: ' + str(ComicID))
mylar.updater.dbUpdate(ComicIDList=cid, calledfrom='dupechk')
return duplicate_filecheck(filename, ComicID, IssueID, StoryArcID)
else:
if rtnval is not None:
if rtnval['action'] == 'dont_dupe':
logger.fdebug('[DUPECHECK] File is Archived but no file can be located within the db at the specified location. Assuming this was a manual archival and will not post-process this issue.')
return rtnval
else:
rtnval = {'action': "dont_dupe"}
#file is Archived, but no entry exists in the db for the location. Assume Archived, and don't post-process.
#quick rescan of files in dir, then rerun the dup check again...
mylar.updater.forceRescan(ComicID)
chk1 = duplicate_filecheck(filename, ComicID, IssueID, StoryArcID, rtnval)
rtnval = chk1
else:
rtnval = {'action': "dupe_file",
'to_dupe': os.path.join(series['ComicLocation'], dupchk['Location'])}
else:
logger.info('[DUPECHECK] Existing file within db :' + dupchk['Location'] + ' has a filesize of : ' + str(dupsize) + ' bytes.')
#keywords to force keep / delete
#this will be eventually user-controlled via the GUI once the options are enabled.
if int(dupsize) == 0:
logger.info('[DUPECHECK] Existing filesize is 0 as I cannot locate the original entry.')
if dupchk['Status'] == 'Archived':
logger.info('[DUPECHECK] Assuming issue is Archived.')
rtnval = {'action': "dupe_file",
'to_dupe': filename}
return rtnval
else:
logger.info('[DUPECHECK] Assuming 0-byte file - this one is gonna get hammered.')
logger.fdebug('[DUPECHECK] Based on duplication preferences I will retain based on : ' + mylar.CONFIG.DUPECONSTRAINT)
tmp_dupeconstraint = mylar.CONFIG.DUPECONSTRAINT
if any(['cbr' in mylar.CONFIG.DUPECONSTRAINT, 'cbz' in mylar.CONFIG.DUPECONSTRAINT]):
if 'cbr' in mylar.CONFIG.DUPECONSTRAINT:
if filename.endswith('.cbr'):
#this has to be configured in config - either retain cbr or cbz.
if dupchk['Location'].endswith('.cbr'):
logger.info('[DUPECHECK-CBR PRIORITY] [#' + dupchk['Issue_Number'] + '] BOTH files are in cbr format. Retaining the larger filesize of the two.')
tmp_dupeconstraint = 'filesize'
else:
#keep filename
logger.info('[DUPECHECK-CBR PRIORITY] [#' + dupchk['Issue_Number'] + '] Retaining newly scanned in file : ' + filename)
rtnval = {'action': "dupe_src",
'to_dupe': os.path.join(series['ComicLocation'], dupchk['Location'])}
else:
if dupchk['Location'].endswith('.cbz'):
logger.info('[DUPECHECK-CBR PRIORITY] [#' + dupchk['Issue_Number'] + '] BOTH files are in cbz format. Retaining the larger filesize of the two.')
tmp_dupeconstraint = 'filesize'
else:
#keep filename
logger.info('[DUPECHECK-CBR PRIORITY] [#' + dupchk['Issue_Number'] + '] Retaining newly scanned in file : ' + dupchk['Location'])
rtnval = {'action': "dupe_file",
'to_dupe': filename}
elif 'cbz' in mylar.CONFIG.DUPECONSTRAINT:
if filename.endswith('.cbr'):
if dupchk['Location'].endswith('.cbr'):
logger.info('[DUPECHECK-CBZ PRIORITY] [#' + dupchk['Issue_Number'] + '] BOTH files are in cbr format. Retaining the larger filesize of the two.')
tmp_dupeconstraint = 'filesize'
else:
#keep filename
logger.info('[DUPECHECK-CBZ PRIORITY] [#' + dupchk['Issue_Number'] + '] Retaining currently scanned in filename : ' + dupchk['Location'])
rtnval = {'action': "dupe_file",
'to_dupe': filename}
else:
if dupchk['Location'].endswith('.cbz'):
logger.info('[DUPECHECK-CBZ PRIORITY] [#' + dupchk['Issue_Number'] + '] BOTH files are in cbz format. Retaining the larger filesize of the two.')
tmp_dupeconstraint = 'filesize'
else:
#keep filename
logger.info('[DUPECHECK-CBZ PRIORITY] [#' + dupchk['Issue_Number'] + '] Retaining newly scanned in filename : ' + filename)
rtnval = {'action': "dupe_src",
'to_dupe': os.path.join(series['ComicLocation'], dupchk['Location'])}
if mylar.CONFIG.DUPECONSTRAINT == 'filesize' or tmp_dupeconstraint == 'filesize':
if filesz <= int(dupsize) and int(dupsize) != 0:
logger.info('[DUPECHECK-FILESIZE PRIORITY] [#' + dupchk['Issue_Number'] + '] Retaining currently scanned in filename : ' + dupchk['Location'])
rtnval = {'action': "dupe_file",
'to_dupe': filename}
else:
logger.info('[DUPECHECK-FILESIZE PRIORITY] [#' + dupchk['Issue_Number'] + '] Retaining newly scanned in filename : ' + filename)
rtnval = {'action': "dupe_src",
'to_dupe': os.path.join(series['ComicLocation'], dupchk['Location'])}
else:
logger.info('[DUPECHECK] Duplication detection returned no hits. This is not a duplicate of anything that I have scanned in as of yet.')
rtnval = {'action': "write"}
return rtnval
def create_https_certificates(ssl_cert, ssl_key):
"""
Create a pair of self-signed HTTPS certificares and store in them in
'ssl_cert' and 'ssl_key'. Method assumes pyOpenSSL is installed.
This code is stolen from SickBeard (http://github.com/midgetspy/Sick-Beard).
"""
from OpenSSL import crypto
from certgen import createKeyPair, createCertRequest, createCertificate, \
TYPE_RSA, serial
# Create the CA Certificate
cakey = createKeyPair(TYPE_RSA, 2048)
careq = createCertRequest(cakey, CN="Certificate Authority")
cacert = createCertificate(careq, (careq, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years
pkey = createKeyPair(TYPE_RSA, 2048)
req = createCertRequest(pkey, CN="Mylar")
cert = createCertificate(req, (cacert, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years
# Save the key and certificate to disk
try:
with open(ssl_key, "w") as fp:
fp.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
with open(ssl_cert, "w") as fp:
fp.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
except IOError as e:
logger.error("Error creating SSL key and certificate: %s", e)
return False
return True
def torrent_create(site, linkid, alt=None):
if any([site == '32P', site == 'TOR']):
pass
#elif site == 'TPSE':
# if alt is None:
# url = mylar.TPSEURL + 'torrent/' + str(linkid) + '.torrent'
# else:
# url = mylar.TPSEURL + 'torrent/' + str(linkid) + '.torrent'
elif site == 'DEM':
url = mylar.DEMURL + 'files/download/' + str(linkid) + '/'
elif site == 'WWT':
url = mylar.WWTURL + 'download.php'
return url
def parse_32pfeed(rssfeedline):
KEYS_32P = {}
if mylar.CONFIG.ENABLE_32P and len(rssfeedline) > 1:
userid_st = rssfeedline.find('&user')
userid_en = rssfeedline.find('&', userid_st +1)
if userid_en == -1:
USERID_32P = rssfeedline[userid_st +6:]
else:
USERID_32P = rssfeedline[userid_st +6:userid_en]
auth_st = rssfeedline.find('&auth')
auth_en = rssfeedline.find('&', auth_st +1)
if auth_en == -1:
AUTH_32P = rssfeedline[auth_st +6:]
else:
AUTH_32P = rssfeedline[auth_st +6:auth_en]
authkey_st = rssfeedline.find('&authkey')
authkey_en = rssfeedline.find('&', authkey_st +1)
if authkey_en == -1:
AUTHKEY_32P = rssfeedline[authkey_st +9:]
else:
AUTHKEY_32P = rssfeedline[authkey_st +9:authkey_en]
KEYS_32P = {"user": USERID_32P,
"auth": AUTH_32P,
"authkey": AUTHKEY_32P,
"passkey": mylar.CONFIG.PASSKEY_32P}
return KEYS_32P
def humanize_time(amount, units = 'seconds'):
def process_time(amount, units):
INTERVALS = [ 1, 60,
60*60,
60*60*24,
60*60*24*7,
60*60*24*7*4,
60*60*24*7*4*12,
60*60*24*7*4*12*100,
60*60*24*7*4*12*100*10]
NAMES = [('second', 'seconds'),
('minute', 'minutes'),
('hour', 'hours'),
('day', 'days'),
('week', 'weeks'),
('month', 'months'),
('year', 'years'),
('century', 'centuries'),
('millennium', 'millennia')]
result = []
unit = map(lambda a: a[1], NAMES).index(units)
# Convert to seconds
amount = amount * INTERVALS[unit]
for i in range(len(NAMES)-1, -1, -1):
a = amount // INTERVALS[i]
if a > 0:
result.append( (a, NAMES[i][1 % a]) )
amount -= a * INTERVALS[i]
return result
rd = process_time(int(amount), units)
cont = 0
for u in rd:
if u[0] > 0:
cont += 1
buf = ''
i = 0
for u in rd:
if u[0] > 0:
buf += "%d %s" % (u[0], u[1])
cont -= 1
if i < (len(rd)-1):
if cont > 1:
buf += ", "
else:
buf += " and "
i += 1
return buf
def issue_status(IssueID):
#import db
myDB = db.DBConnection()
IssueID = str(IssueID)
logger.fdebug('[ISSUE-STATUS] Issue Status Check for %s' % IssueID)
isschk = myDB.selectone("SELECT * FROM issues WHERE IssueID=?", [IssueID]).fetchone()
if isschk is None:
isschk = myDB.selectone("SELECT * FROM annuals WHERE IssueID=?", [IssueID]).fetchone()
if isschk is None:
isschk = myDB.selectone("SELECT * FROM storyarcs WHERE IssueArcID=?", [IssueID]).fetchone()
if isschk is None:
logger.warn('Unable to retrieve IssueID from db. This is a problem. Aborting.')
return False
if any([isschk['Status'] == 'Downloaded', isschk['Status'] == 'Snatched']):
return True
else:
return False
def crc(filename):
#memory in lieu of speed (line by line)
#prev = 0
#for eachLine in open(filename,"rb"):
# prev = zlib.crc32(eachLine, prev)
#return "%X"%(prev & 0xFFFFFFFF)
#speed in lieu of memory (file into memory entirely)
#return "%X" % (zlib.crc32(open(filename, "rb").read()) & 0xFFFFFFFF)
filename = filename.encode(mylar.SYS_ENCODING)
return hashlib.md5(filename).hexdigest()
def issue_find_ids(ComicName, ComicID, pack, IssueNumber):
#import db
myDB = db.DBConnection()
issuelist = myDB.select("SELECT * FROM issues WHERE ComicID=?", [ComicID])
if 'Annual' not in pack:
packlist = [x.strip() for x in pack.split(',')]
plist = []
pack_issues = []
for pl in packlist:
if '-' in pl:
plist.append(range(int(pl[:pl.find('-')]),int(pl[pl.find('-')+1:])+1))
else:
plist.append(int(pl))
for pi in plist:
if type(pi) == list:
for x in pi:
pack_issues.append(x)
else:
pack_issues.append(pi)
pack_issues.sort()
annualize = False
else:
#remove the annuals wording
tmp_annuals = pack[pack.find('Annual'):]
tmp_ann = re.sub('[annual/annuals/+]', '', tmp_annuals.lower()).strip()
tmp_pack = re.sub('[annual/annuals/+]', '', pack.lower()).strip()
pack_issues_numbers = re.findall(r'\d+', tmp_pack)
pack_issues = range(int(pack_issues_numbers[0]),int(pack_issues_numbers[1])+1)
annualize = True
issues = {}
issueinfo = []
Int_IssueNumber = issuedigits(IssueNumber)
valid = False
for iss in pack_issues:
int_iss = issuedigits(iss)
for xb in issuelist:
if xb['Status'] != 'Downloaded':
if xb['Int_IssueNumber'] == int_iss:
issueinfo.append({'issueid': xb['IssueID'],
'int_iss': int_iss,
'issuenumber': xb['Issue_Number']})
break
for x in issueinfo:
if Int_IssueNumber == x['int_iss']:
valid = True
break
issues['issues'] = issueinfo
if len(issues['issues']) == len(pack_issues):
logger.info('Complete issue count of ' + str(len(pack_issues)) + ' issues are available within this pack for ' + ComicName)
else:
logger.info('Issue counts are not complete (not a COMPLETE pack) for ' + ComicName)
issues['issue_range'] = pack_issues
issues['valid'] = valid
return issues
def conversion(value):
if type(value) == str:
try:
value = value.decode('utf-8')
except:
value = value.decode('windows-1252')
return value
def clean_url(url):
leading = len(url) - len(url.lstrip(' '))
ending = len(url) - len(url.rstrip(' '))
if leading >= 1:
url = url[leading:]
if ending >=1:
url = url[:-ending]
return url
def chunker(seq, size):
#returns a list from a large group of tuples by size (ie. for group in chunker(seq, 3))
return [seq[pos:pos + size] for pos in xrange(0, len(seq), size)]
def cleanHost(host, protocol = True, ssl = False, username = None, password = None):
""" Return a cleaned up host with given url options set
taken verbatim from CouchPotato
Changes protocol to https if ssl is set to True and http if ssl is set to false.
>>> cleanHost("localhost:80", ssl=True)
'https://localhost:80/'
>>> cleanHost("localhost:80", ssl=False)
'http://localhost:80/'
Username and password is managed with the username and password variables
>>> cleanHost("localhost:80", username="user", password="passwd")
'http://user:passwd@localhost:80/'
Output without scheme (protocol) can be forced with protocol=False
>>> cleanHost("localhost:80", protocol=False)
'localhost:80'
"""
if not '://' in host and protocol:
host = ('https://' if ssl else 'http://') + host
if not protocol:
host = host.split('://', 1)[-1]
if protocol and username and password:
try:
auth = re.findall('^(?:.+?//)(.+?):(.+?)@(?:.+)$', host)
if auth:
log.error('Cleanhost error: auth already defined in url: %s, please remove BasicAuth from url.', host)
else:
host = host.replace('://', '://%s:%s@' % (username, password), 1)
except:
pass
host = host.rstrip('/ ')
if protocol:
host += '/'
return host
def checkthe_id(comicid=None, up_vals=None):
#import db
myDB = db.DBConnection()
if not up_vals:
chk = myDB.selectone("SELECT * from ref32p WHERE ComicID=?", [comicid]).fetchone()
if chk is None:
return None
else:
#if updated time hasn't been set or it's > 24 hrs, blank the entry so we can make sure we pull an updated groupid from 32p
if chk['Updated'] is None:
logger.fdebug('Reference found for 32p - but the id has never been verified after populating. Verifying it is still the right id before proceeding.')
return None
else:
c_obj_date = datetime.datetime.strptime(chk['Updated'], "%Y-%m-%d %H:%M:%S")
n_date = datetime.datetime.now()
absdiff = abs(n_date - c_obj_date)
hours = (absdiff.days * 24 * 60 * 60 + absdiff.seconds) / 3600.0
if hours >= 24:
logger.fdebug('Reference found for 32p - but older than 24hours since last checked. Verifying it is still the right id before proceeding.')
return None
else:
return {'id': chk['ID'],
'series': chk['Series']}
else:
ctrlVal = {'ComicID': comicid}
newVal = {'Series': up_vals[0]['series'],
'ID': up_vals[0]['id'],
'Updated': now()}
myDB.upsert("ref32p", newVal, ctrlVal)
def updatearc_locs(storyarcid, issues):
#import db
myDB = db.DBConnection()
issuelist = []
for x in issues:
issuelist.append(x['IssueID'])
tmpsql = "SELECT a.comicid, a.comiclocation, b.comicid, b.status, b.issueid, b.location FROM comics as a INNER JOIN issues as b ON a.comicid = b.comicid WHERE b.issueid in ({seq})".format(seq=','.join(['?'] *(len(issuelist))))
chkthis = myDB.select(tmpsql, issuelist)
update_iss = []
if chkthis is None:
return
else:
for chk in chkthis:
if chk['Status'] == 'Downloaded':
pathsrc = os.path.join(chk['ComicLocation'], chk['Location'])
if not os.path.exists(pathsrc):
try:
if all([mylar.CONFIG.MULTIPLE_DEST_DIRS is not None, mylar.CONFIG.MULTIPLE_DEST_DIRS != 'None', os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(chk['ComicLocation'])) != chk['ComicLocation'], os.path.exists(os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(chk['ComicLocation'])))]):
pathsrc = os.path.join(mylar.CONFIG.MULTIPLE_DEST_DIRS, os.path.basename(chk['ComicLocation']), chk['Location'])
else:
logger.fdebug(module + ' file does not exist in location: ' + pathdir + '. Cannot valid location - some options will not be available for this item.')
continue
except:
continue
# update_iss.append({'IssueID': chk['IssueID'],
# 'Location': pathdir})
arcinfo = None
for la in issues:
if la['IssueID'] == chk['IssueID']:
arcinfo = la
break
if arcinfo is None:
continue
if arcinfo['Publisher'] is None:
arcpub = arcinfo['IssuePublisher']
else:
arcpub = arcinfo['Publisher']
grdst = arcformat(arcinfo['StoryArc'], spantheyears(arcinfo['StoryArcID']), arcpub)
if grdst is not None:
logger.info('grdst:' + grdst)
#send to renamer here if valid.
dfilename = chk['Location']
if mylar.CONFIG.RENAME_FILES:
renamed_file = rename_param(arcinfo['ComicID'], arcinfo['ComicName'], arcinfo['IssueNumber'], chk['Location'], issueid=arcinfo['IssueID'], arc=arcinfo['StoryArc'])
if renamed_file:
dfilename = renamed_file['nfilename']
if mylar.CONFIG.READ2FILENAME:
#logger.fdebug('readingorder#: ' + str(arcinfo['ReadingOrder']))
#if int(arcinfo['ReadingOrder']) < 10: readord = "00" + str(arcinfo['ReadingOrder'])
#elif int(arcinfo['ReadingOrder']) >= 10 and int(arcinfo['ReadingOrder']) <= 99: readord = "0" + str(arcinfo['ReadingOrder'])
#else: readord = str(arcinfo['ReadingOrder'])
readord = renamefile_readingorder(arcinfo['ReadingOrder'])
dfilename = str(readord) + "-" + dfilename
pathdst = os.path.join(grdst, dfilename)
logger.fdebug('Destination Path : ' + pathdst)
logger.fdebug('Source Path : ' + pathsrc)
if not os.path.isdir(grdst):
logger.fdebug('[ARC-DIRECTORY] Arc directory doesn\'t exist. Creating: %s' % grdst)
mylar.filechecker.validateAndCreateDirectory(grdst, create=True)
if not os.path.isfile(pathdst):
logger.info('[' + mylar.CONFIG.ARC_FILEOPS.upper() + '] ' + pathsrc + ' into directory : ' + pathdst)
try:
#need to ensure that src is pointing to the series in order to do a soft/hard-link properly
fileoperation = file_ops(pathsrc, pathdst, arc=True)
if not fileoperation:
raise OSError
except (OSError, IOError):
logger.fdebug('[' + mylar.CONFIG.ARC_FILEOPS.upper() + '] Failure ' + pathsrc + ' - check directories and manually re-run.')
continue
updateloc = pathdst
else:
updateloc = pathsrc
update_iss.append({'IssueID': chk['IssueID'],
'Location': updateloc})
for ui in update_iss:
logger.info(ui['IssueID'] + ' to update location to: ' + ui['Location'])
myDB.upsert("storyarcs", {'Location': ui['Location']}, {'IssueID': ui['IssueID'], 'StoryArcID': storyarcid})
def spantheyears(storyarcid):
#import db
myDB = db.DBConnection()
totalcnt = myDB.select("SELECT * FROM storyarcs WHERE StoryArcID=?", [storyarcid])
lowyear = 9999
maxyear = 0
for la in totalcnt:
if la['IssueDate'] is None or la['IssueDate'] == '0000-00-00':
continue
else:
if int(la['IssueDate'][:4]) > maxyear:
maxyear = int(la['IssueDate'][:4])
if int(la['IssueDate'][:4]) < lowyear:
lowyear = int(la['IssueDate'][:4])
if maxyear == 0:
spanyears = la['SeriesYear']
elif lowyear == maxyear:
spanyears = str(maxyear)
else:
spanyears = str(lowyear) + ' - ' + str(maxyear) #la['SeriesYear'] + ' - ' + str(maxyear)
return spanyears
def arcformat(arc, spanyears, publisher):
arcdir = filesafe(arc)
if publisher is None:
publisher = 'None'
values = {'$arc': arcdir,
'$spanyears': spanyears,
'$publisher': publisher}
tmp_folderformat = mylar.CONFIG.ARC_FOLDERFORMAT
if publisher == 'None':
chunk_f_f = re.sub('\$publisher', '', tmp_folderformat)
chunk_f = re.compile(r'\s+')
tmp_folderformat = chunk_f.sub(' ', chunk_f_f)
if any([tmp_folderformat == '', tmp_folderformat is None]):
arcpath = arcdir
else:
arcpath = replace_all(tmp_folderformat, values)
if mylar.CONFIG.REPLACE_SPACES:
arcpath = arcpath.replace(' ', mylar.CONFIG.REPLACE_CHAR)
if arcpath.startswith('/'):
arcpath = arcpath[1:]
elif arcpath.startswith('//'):
arcpath = arcpath[2:]
if mylar.CONFIG.STORYARCDIR is True:
dstloc = os.path.join(mylar.CONFIG.DESTINATION_DIR, 'StoryArcs', arcpath)
elif mylar.CONFIG.COPY2ARCDIR is True:
logger.warn('Story arc directory is not configured. Defaulting to grabbag directory: ' + mylar.CONFIG.GRABBAG_DIR)
dstloc = os.path.join(mylar.CONFIG.GRABBAG_DIR, arcpath)
else:
dstloc = None
return dstloc
def torrentinfo(issueid=None, torrent_hash=None, download=False, monitor=False):
#import db
from base64 import b16encode, b32decode
#check the status of the issueid to make sure it's in Snatched status and was grabbed via torrent.
if issueid:
myDB = db.DBConnection()
cinfo = myDB.selectone('SELECT a.Issue_Number, a.ComicName, a.Status, b.Hash from issues as a inner join snatched as b ON a.IssueID=b.IssueID WHERE a.IssueID=?', [issueid]).fetchone()
if cinfo is None:
logger.warn('Unable to locate IssueID of : ' + issueid)
snatch_status = 'ERROR'
if cinfo['Status'] != 'Snatched' or cinfo['Hash'] is None:
logger.warn(cinfo['ComicName'] + ' #' + cinfo['Issue_Number'] + ' is currently in a ' + cinfo['Status'] + ' Status.')
snatch_status = 'ERROR'
torrent_hash = cinfo['Hash']
logger.fdebug("Working on torrent: " + torrent_hash)
if len(torrent_hash) == 32:
torrent_hash = b16encode(b32decode(torrent_hash))
if not len(torrent_hash) == 40:
logger.error("Torrent hash is missing, or an invalid hash value has been passed")
snatch_status = 'ERROR'
else:
if mylar.USE_RTORRENT:
import test
rp = test.RTorrent()
torrent_info = rp.main(torrent_hash, check=True)
elif mylar.USE_DELUGE:
#need to set the connect here as well....
import torrent.clients.deluge as delu
dp = delu.TorrentClient()
if not dp.connect(mylar.CONFIG.DELUGE_HOST, mylar.CONFIG.DELUGE_USERNAME, mylar.CONFIG.DELUGE_PASSWORD):
logger.warn('Not connected to Deluge!')
torrent_info = dp.get_torrent(torrent_hash)
else:
snatch_status = 'ERROR'
return
logger.info('torrent_info: %s' % torrent_info)
if torrent_info is False or len(torrent_info) == 0:
logger.warn('torrent returned no information. Check logs - aborting auto-snatch at this time.')
snatch_status = 'ERROR'
else:
if mylar.USE_DELUGE:
torrent_status = torrent_info['is_finished']
torrent_files = torrent_info['num_files']
torrent_folder = torrent_info['save_path']
torrent_info['total_filesize'] = torrent_info['total_size']
torrent_info['upload_total'] = torrent_info['total_uploaded']
torrent_info['download_total'] = torrent_info['total_payload_download']
torrent_info['time_started'] = torrent_info['time_added']
elif mylar.USE_RTORRENT:
torrent_status = torrent_info['completed']
torrent_files = len(torrent_info['files'])
torrent_folder = torrent_info['folder']
if all([torrent_status is True, download is True]):
if not issueid:
torrent_info['snatch_status'] = 'STARTING...'
#yield torrent_info
import shlex, subprocess
logger.info('Torrent is completed and status is currently Snatched. Attempting to auto-retrieve.')
with open(mylar.CONFIG.AUTO_SNATCH_SCRIPT, 'r') as f:
first_line = f.readline()
if mylar.CONFIG.AUTO_SNATCH_SCRIPT.endswith('.sh'):
shell_cmd = re.sub('#!', '', first_line)
if shell_cmd == '' or shell_cmd is None:
shell_cmd = '/bin/bash'
else:
shell_cmd = sys.executable
curScriptName = shell_cmd + ' ' + str(mylar.CONFIG.AUTO_SNATCH_SCRIPT).decode("string_escape")
if torrent_files > 1:
downlocation = torrent_folder.encode('utf-8')
else:
if mylar.USE_DELUGE:
downlocation = os.path.join(torrent_folder.encode('utf-8'), torrent_info['files'][0]['path'])
else:
downlocation = torrent_info['files'][0].encode('utf-8')
autosnatch_env = os.environ.copy()
autosnatch_env['downlocation'] = re.sub("'", "\\'",downlocation)
#these are pulled from the config and are the ssh values to use to retrieve the data
autosnatch_env['host'] = mylar.CONFIG.PP_SSHHOST
autosnatch_env['port'] = mylar.CONFIG.PP_SSHPORT
autosnatch_env['user'] = mylar.CONFIG.PP_SSHUSER
autosnatch_env['localcd'] = mylar.CONFIG.PP_SSHLOCALCD
#bash won't accept None, so send check and send empty strings for the 2 possible None values if needed
if mylar.CONFIG.PP_SSHKEYFILE is not None:
autosnatch_env['keyfile'] = mylar.CONFIG.PP_SSHKEYFILE
else:
autosnatch_env['keyfile'] = ''
if mylar.CONFIG.PP_SSHPASSWD is not None:
autosnatch_env['passwd'] = mylar.CONFIG.PP_SSHPASSWD
else:
autosnatch_env['passwd'] = ''
#downlocation = re.sub("\'", "\\'", downlocation)
#downlocation = re.sub("&", "\&", downlocation)
script_cmd = shlex.split(curScriptName, posix=False) # + [downlocation]
logger.fdebug(u"Executing command " +str(script_cmd))
try:
p = subprocess.Popen(script_cmd, env=dict(autosnatch_env), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=mylar.PROG_DIR)
out, err = p.communicate()
logger.fdebug(u"Script result: " + out)
except OSError, e:
logger.warn(u"Unable to run extra_script: " + e)
snatch_status = 'ERROR'
else:
if 'Access failed: No such file' in out:
logger.fdebug('Not located in location it is supposed to be in - probably has been moved by some script and I got the wrong location due to timing. Trying again...')
snatch_status = 'IN PROGRESS'
else:
snatch_status = 'COMPLETED'
torrent_info['completed'] = torrent_status
torrent_info['files'] = torrent_files
torrent_info['folder'] = torrent_folder
else:
if download is True:
snatch_status = 'IN PROGRESS'
elif monitor is True:
#pause the torrent, copy it to the cache folder, unpause the torrent and return the complete path to the cache location
if mylar.USE_DELUGE:
pauseit = dp.stop_torrent(torrent_hash)
if pauseit is False:
logger.warn('Unable to pause torrent - cannot run post-process on item at this time.')
snatch_status = 'MONITOR FAIL'
else:
try:
new_filepath = os.path.join(torrent_path, '.copy')
logger.fdebug('New_Filepath: %s' % new_filepath)
shutil.copy(torrent_path, new_filepath)
torrent_info['copied_filepath'] = new_filepath
except:
logger.warn('Unexpected Error: %s' % sys.exc_info()[0])
logger.warn('Unable to create temporary directory to perform meta-tagging. Processing cannot continue with given item at this time.')
torrent_info['copied_filepath'] = torrent_path
SNATCH_STATUS = 'MONITOR FAIL'
else:
startit = dp.start_torrent(torrent_hash)
SNATCH_STATUS = 'MONITOR COMPLETE'
else:
snatch_status = 'NOT SNATCHED'
torrent_info['snatch_status'] = snatch_status
return torrent_info
def weekly_info(week=None, year=None, current=None):
#find the current week and save it as a reference point.
todaydate = datetime.datetime.today()
current_weeknumber = todaydate.strftime("%U")
if current is not None:
c_weeknumber = int(current[:current.find('-')])
c_weekyear = int(current[current.find('-')+1:])
else:
c_weeknumber = week
c_weekyear = year
if week:
weeknumber = int(week)
year = int(year)
#monkey patch for 2018/2019 - week 52/week 0
if all([weeknumber == 52, c_weeknumber == 51, c_weekyear == 2018]):
weeknumber = 0
year = 2019
elif all([weeknumber == 52, c_weeknumber == 0, c_weekyear == 2019]):
weeknumber = 51
year = 2018
#monkey patch for 2019/2020 - week 52/week 0
if all([weeknumber == 52, c_weeknumber == 51, c_weekyear == 2019]):
weeknumber = 0
year = 2020
elif all([weeknumber == 52, c_weeknumber == 0, c_weekyear == 2020]):
weeknumber = 51
year = 2019
#view specific week (prev_week, next_week)
startofyear = date(year,1,1)
week0 = startofyear - timedelta(days=startofyear.isoweekday())
stweek = datetime.datetime.strptime(week0.strftime('%Y-%m-%d'), '%Y-%m-%d')
startweek = stweek + timedelta(weeks = weeknumber)
midweek = startweek + timedelta(days = 3)
endweek = startweek + timedelta(days = 6)
else:
#find the given week number for the current day
weeknumber = current_weeknumber
year = todaydate.strftime("%Y")
#monkey patch for 2018/2019 - week 52/week 0
if all([weeknumber == 52, c_weeknumber == 51, c_weekyear == 2018]):
weeknumber = 0
year = 2019
elif all([weeknumber == 52, c_weeknumber == 0, c_weekyear == 2019]):
weeknumber = 51
year = 2018
#monkey patch for 2019/2020 - week 52/week 0
if all([weeknumber == 52, c_weeknumber == 51, c_weekyear == 2019]) or all([weeknumber == '52', year == '2019']):
weeknumber = 0
year = 2020
elif all([weeknumber == 52, c_weeknumber == 0, c_weekyear == 2020]):
weeknumber = 51
year = 2019
stweek = datetime.datetime.strptime(todaydate.strftime('%Y-%m-%d'), '%Y-%m-%d')
startweek = stweek - timedelta(days = (stweek.weekday() + 1) % 7)
midweek = startweek + timedelta(days = 3)
endweek = startweek + timedelta(days = 6)
prev_week = int(weeknumber) - 1
prev_year = year
if prev_week < 0:
prev_week = 52
prev_year = int(year) - 1
next_week = int(weeknumber) + 1
next_year = year
if next_week > 52:
next_year = int(year) + 1
next_week = datetime.date(int(next_year),1,1).strftime("%U")
date_fmt = "%B %d, %Y"
try:
con_startweek = u"" + startweek.strftime(date_fmt).decode('utf-8')
con_endweek = u"" + endweek.strftime(date_fmt).decode('utf-8')
except:
con_startweek = u"" + startweek.strftime(date_fmt).decode('cp1252')
con_endweek = u"" + endweek.strftime(date_fmt).decode('cp1252')
if mylar.CONFIG.WEEKFOLDER_LOC is not None:
weekdst = mylar.CONFIG.WEEKFOLDER_LOC
else:
weekdst = mylar.CONFIG.DESTINATION_DIR
if mylar.SCHED_WEEKLY_LAST is not None:
weekly_stamp = datetime.datetime.fromtimestamp(mylar.SCHED_WEEKLY_LAST)
weekly_last = weekly_stamp.replace(microsecond=0)
else:
weekly_last = 'None'
weekinfo = {'weeknumber': weeknumber,
'startweek': con_startweek,
'midweek': midweek.strftime('%Y-%m-%d'),
'endweek': con_endweek,
'year': year,
'prev_weeknumber': prev_week,
'prev_year': prev_year,
'next_weeknumber': next_week,
'next_year': next_year,
'current_weeknumber': current_weeknumber,
'last_update': weekly_last}
if weekdst is not None:
if mylar.CONFIG.WEEKFOLDER_FORMAT == 0:
weekn = weeknumber
if len(str(weekn)) == 1:
weekn = '%s%s' % ('0', str(weekn))
weekfold = os.path.join(weekdst, '%s-%s' % (weekinfo['year'], weekn))
else:
weekfold = os.path.join(weekdst, str( str(weekinfo['midweek']) ))
else:
weekfold = None
weekinfo['week_folder'] = weekfold
return weekinfo
def latestdate_update():
#import db
myDB = db.DBConnection()
ccheck = myDB.select('SELECT a.ComicID, b.IssueID, a.LatestDate, b.ReleaseDate, b.Issue_Number from comics as a left join issues as b on a.comicid=b.comicid where a.LatestDate < b.ReleaseDate or a.LatestDate like "%Unknown%" group by a.ComicID')
if ccheck is None or len(ccheck) == 0:
return
logger.info('Now preparing to update ' + str(len(ccheck)) + ' series that have out-of-date latest date information.')
ablist = []
for cc in ccheck:
ablist.append({'ComicID': cc['ComicID'],
'LatestDate': cc['ReleaseDate'],
'LatestIssue': cc['Issue_Number']})
#forcibly set the latest date and issue number to the most recent.
for a in ablist:
logger.info(a)
newVal = {'LatestDate': a['LatestDate'],
'LatestIssue': a['LatestIssue']}
ctrlVal = {'ComicID': a['ComicID']}
logger.info('updating latest date for : ' + a['ComicID'] + ' to ' + a['LatestDate'] + ' #' + a['LatestIssue'])
myDB.upsert("comics", newVal, ctrlVal)
def ddl_downloader(queue):
myDB = db.DBConnection()
while True:
if mylar.DDL_LOCK is True:
time.sleep(5)
elif mylar.DDL_LOCK is False and queue.qsize() >= 1:
item = queue.get(True)
if item == 'exit':
logger.info('Cleaning up workers for shutdown')
break
logger.info('Now loading request from DDL queue: %s' % item['series'])
#write this to the table so we have a record of what's going on.
ctrlval = {'id': item['id']}
val = {'status': 'Downloading',
'updated_date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}
myDB.upsert('ddl_info', val, ctrlval)
ddz = getcomics.GC()
ddzstat = ddz.downloadit(item['id'], item['link'], item['mainlink'], item['resume'])
if ddzstat['success'] is True:
tdnow = datetime.datetime.now()
nval = {'status': 'Completed',
'updated_date': tdnow.strftime('%Y-%m-%d %H:%M')}
myDB.upsert('ddl_info', nval, ctrlval)
if all([ddzstat['success'] is True, mylar.CONFIG.POST_PROCESSING is True]):
try:
if ddzstat['filename'] is None:
logger.info('%s successfully downloaded - now initiating post-processing.' % (os.path.basename(ddzstat['path'])))
mylar.PP_QUEUE.put({'nzb_name': os.path.basename(ddzstat['path']),
'nzb_folder': ddzstat['path'],
'failed': False,
'issueid': None,
'comicid': item['comicid'],
'apicall': True,
'ddl': True})
else:
logger.info('%s successfully downloaded - now initiating post-processing.' % (ddzstat['filename']))
mylar.PP_QUEUE.put({'nzb_name': ddzstat['filename'],
'nzb_folder': ddzstat['path'],
'failed': False,
'issueid': item['issueid'],
'comicid': item['comicid'],
'apicall': True,
'ddl': True})
except Exception as e:
logger.info('process error: %s [%s]' %(e, ddzstat))
elif all([ddzstat['success'] is True, mylar.CONFIG.POST_PROCESSING is False]):
logger.info('File successfully downloaded. Post Processing is not enabled - item retained here: %s' % os.path.join(ddzstat['path'],ddzstat['filename']))
else:
logger.info('[Status: %s] Failed to download: %s ' % (ddzstat['success'], ddzstat))
nval = {'status': 'Failed',
'updated_date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}
myDB.upsert('ddl_info', nval, ctrlval)
else:
time.sleep(5)
def postprocess_main(queue):
while True:
if mylar.APILOCK is True:
time.sleep(5)
elif mylar.APILOCK is False and queue.qsize() >= 1: #len(queue) > 1:
pp = None
item = queue.get(True)
logger.info('Now loading from post-processing queue: %s' % item)
if item == 'exit':
logger.info('Cleaning up workers for shutdown')
break
if mylar.APILOCK is False:
try:
pprocess = process.Process(item['nzb_name'], item['nzb_folder'], item['failed'], item['issueid'], item['comicid'], item['apicall'], item['ddl'])
except:
pprocess = process.Process(item['nzb_name'], item['nzb_folder'], item['failed'], item['issueid'], item['comicid'], item['apicall'])
pp = pprocess.post_process()
time.sleep(5) #arbitrary sleep to let the process attempt to finish pp'ing
if pp is not None:
if pp['mode'] == 'stop':
#reset the lock so any subsequent items can pp and not keep the queue locked up.
mylar.APILOCK = False
if mylar.APILOCK is True:
logger.info('Another item is post-processing still...')
time.sleep(15)
#mylar.PP_QUEUE.put(item)
else:
time.sleep(5)
def search_queue(queue):
while True:
if mylar.SEARCHLOCK is True:
time.sleep(5)
elif mylar.SEARCHLOCK is False and queue.qsize() >= 1: #len(queue) > 1:
item = queue.get(True)
if item == 'exit':
logger.info('[SEARCH-QUEUE] Cleaning up workers for shutdown')
break
logger.info('[SEARCH-QUEUE] Now loading item from search queue: %s' % item)
if mylar.SEARCHLOCK is False:
ss_queue = mylar.search.searchforissue(item['issueid'])
time.sleep(5) #arbitrary sleep to let the process attempt to finish pp'ing
if mylar.SEARCHLOCK is True:
logger.fdebug('[SEARCH-QUEUE] Another item is currently being searched....')
time.sleep(15)
else:
time.sleep(5)
def worker_main(queue):
while True:
if queue.qsize() >= 1:
item = queue.get(True)
logger.info('Now loading from queue: ' + item)
if item == 'exit':
logger.info('Cleaning up workers for shutdown')
break
snstat = torrentinfo(torrent_hash=item, download=True)
if snstat['snatch_status'] == 'IN PROGRESS':
logger.info('Still downloading in client....let us try again momentarily.')
time.sleep(30)
mylar.SNATCHED_QUEUE.put(item)
elif any([snstat['snatch_status'] == 'MONITOR FAIL', snstat['snatch_status'] == 'MONITOR COMPLETE']):
logger.info('File copied for post-processing - submitting as a direct pp.')
threading.Thread(target=self.checkFolder, args=[os.path.abspath(os.path.join(snstat['copied_filepath'], os.pardir))]).start()
else:
time.sleep(15)
def nzb_monitor(queue):
while True:
if queue.qsize() >= 1:
item = queue.get(True)
if item == 'exit':
logger.info('Cleaning up workers for shutdown')
break
logger.info('Now loading from queue: %s' % item)
if all([mylar.USE_SABNZBD is True, mylar.CONFIG.SAB_CLIENT_POST_PROCESSING is True]):
nz = sabnzbd.SABnzbd(item)
nzstat = nz.processor()
elif all([mylar.USE_NZBGET is True, mylar.CONFIG.NZBGET_CLIENT_POST_PROCESSING is True]):
nz = nzbget.NZBGet()
nzstat = nz.processor(item)
else:
logger.warn('There are no NZB Completed Download handlers enabled. Not sending item to completed download handling...')
break
if any([nzstat['status'] == 'file not found', nzstat['status'] == 'double-pp']):
logger.warn('Unable to complete post-processing call due to not finding file in the location provided. [%s]' % item)
elif nzstat['status'] is False:
logger.info('Could not find NZBID %s in the downloader\'s queue. I will requeue this item for post-processing...' % item['NZBID'])
time.sleep(5)
mylar.NZB_QUEUE.put(item)
elif nzstat['status'] is True:
if nzstat['failed'] is False:
logger.info('File successfully downloaded - now initiating completed downloading handling.')
else:
logger.info('File failed either due to being corrupt or incomplete - now initiating completed failed downloading handling.')
try:
mylar.PP_QUEUE.put({'nzb_name': nzstat['name'],
'nzb_folder': nzstat['location'],
'failed': nzstat['failed'],
'issueid': nzstat['issueid'],
'comicid': nzstat['comicid'],
'apicall': nzstat['apicall'],
'ddl': False})
#cc = process.Process(nzstat['name'], nzstat['location'], failed=nzstat['failed'])
#nzpp = cc.post_process()
except Exception as e:
logger.info('process error: %s' % e)
else:
time.sleep(5)
def script_env(mode, vars):
#mode = on-snatch, pre-postprocess, post-postprocess
#var = dictionary containing variables to pass
mylar_env = os.environ.copy()
if mode == 'on-snatch':
runscript = mylar.CONFIG.SNATCH_SCRIPT
if 'torrentinfo' in vars:
if 'hash' in vars['torrentinfo']:
mylar_env['mylar_release_hash'] = vars['torrentinfo']['hash']
if 'torrent_filename' in vars['torrentinfo']:
mylar_env['mylar_torrent_filename'] = vars['torrentinfo']['torrent_filename']
if 'name' in vars['torrentinfo']:
mylar_env['mylar_release_name'] = vars['torrentinfo']['name']
if 'folder' in vars['torrentinfo']:
mylar_env['mylar_release_folder'] = vars['torrentinfo']['folder']
if 'label' in vars['torrentinfo']:
mylar_env['mylar_release_label'] = vars['torrentinfo']['label']
if 'total_filesize' in vars['torrentinfo']:
mylar_env['mylar_release_filesize'] = str(vars['torrentinfo']['total_filesize'])
if 'time_started' in vars['torrentinfo']:
mylar_env['mylar_release_start'] = str(vars['torrentinfo']['time_started'])
if 'filepath' in vars['torrentinfo']:
mylar_env['mylar_torrent_file'] = str(vars['torrentinfo']['filepath'])
else:
try:
mylar_env['mylar_release_files'] = '|'.join(vars['torrentinfo']['files'])
except TypeError:
mylar_env['mylar_release_files'] = '|'.join(json.dumps(vars['torrentinfo']['files']))
elif 'nzbinfo' in vars:
mylar_env['mylar_release_id'] = vars['nzbinfo']['id']
if 'client_id' in vars['nzbinfo']:
mylar_env['mylar_client_id'] = vars['nzbinfo']['client_id']
mylar_env['mylar_release_nzbname'] = vars['nzbinfo']['nzbname']
mylar_env['mylar_release_link'] = vars['nzbinfo']['link']
mylar_env['mylar_release_nzbpath'] = vars['nzbinfo']['nzbpath']
if 'blackhole' in vars['nzbinfo']:
mylar_env['mylar_release_blackhole'] = vars['nzbinfo']['blackhole']
mylar_env['mylar_release_provider'] = vars['provider']
if 'comicinfo' in vars:
try:
if vars['comicinfo']['comicid'] is not None:
mylar_env['mylar_comicid'] = vars['comicinfo']['comicid'] #comicid/issueid are unknown for one-offs (should be fixable tho)
else:
mylar_env['mylar_comicid'] = 'None'
except:
pass
try:
if vars['comicinfo']['issueid'] is not None:
mylar_env['mylar_issueid'] = vars['comicinfo']['issueid']
else:
mylar_env['mylar_issueid'] = 'None'
except:
pass
try:
if vars['comicinfo']['issuearcid'] is not None:
mylar_env['mylar_issuearcid'] = vars['comicinfo']['issuearcid']
else:
mylar_env['mylar_issuearcid'] = 'None'
except:
pass
mylar_env['mylar_comicname'] = vars['comicinfo']['comicname']
mylar_env['mylar_issuenumber'] = str(vars['comicinfo']['issuenumber'])
try:
mylar_env['mylar_comicvolume'] = str(vars['comicinfo']['volume'])
except:
pass
try:
mylar_env['mylar_seriesyear'] = str(vars['comicinfo']['seriesyear'])
except:
pass
try:
mylar_env['mylar_issuedate'] = str(vars['comicinfo']['issuedate'])
except:
pass
mylar_env['mylar_release_pack'] = str(vars['pack'])
if vars['pack'] is True:
if vars['pack_numbers'] is not None:
mylar_env['mylar_release_pack_numbers'] = vars['pack_numbers']
if vars['pack_issuelist'] is not None:
mylar_env['mylar_release_pack_issuelist'] = vars['pack_issuelist']
mylar_env['mylar_method'] = vars['method']
mylar_env['mylar_client'] = vars['clientmode']
elif mode == 'post-process':
#to-do
runscript = mylar.CONFIG.EXTRA_SCRIPTS
elif mode == 'pre-process':
#to-do
runscript = mylar.CONFIG.PRE_SCRIPTS
logger.fdebug('Initiating ' + mode + ' script detection.')
with open(runscript, 'r') as f:
first_line = f.readline()
if runscript.endswith('.sh'):
shell_cmd = re.sub('#!', '', first_line)
if shell_cmd == '' or shell_cmd is None:
shell_cmd = '/bin/bash'
else:
shell_cmd = sys.executable
curScriptName = shell_cmd + ' ' + runscript.decode("string_escape")
logger.fdebug("snatch script detected...enabling: " + str(curScriptName))
script_cmd = shlex.split(curScriptName)
logger.fdebug(u"Executing command " +str(script_cmd))
try:
subprocess.call(script_cmd, env=dict(mylar_env))
except OSError, e:
logger.warn(u"Unable to run extra_script: " + str(script_cmd))
return False
else:
return True
def get_the_hash(filepath):
import bencode
# Open torrent file
torrent_file = open(filepath, "rb")
metainfo = bencode.decode(torrent_file.read())
info = metainfo['info']
thehash = hashlib.sha1(bencode.encode(info)).hexdigest().upper()
logger.info('Hash of file : ' + thehash)
return {'hash': thehash}
def disable_provider(site, newznab=False):
logger.info('Temporarily disabling %s due to not responding' % site)
if newznab is True:
tmplist = []
for ti in mylar.CONFIG.EXTRA_NEWZNABS:
tmpnewz = list(ti)
if tmpnewz[0] == site:
tmpnewz[5] = '0'
tmplist.append(tuple(tmpnewz))
mylar.CONFIG.EXTRA_NEWZNABS = tmplist
else:
if site == 'nzbsu':
mylar.CONFIG.NZBSU = False
elif site == 'dognzb':
mylar.CONFIG.DOGNZB = False
elif site == 'experimental':
mylar.CONFIG.EXPERIMENTAL = False
elif site == '32P':
mylar.CONFIG.ENABLE_32P = False
def date_conversion(originaldate):
c_obj_date = datetime.datetime.strptime(originaldate, "%Y-%m-%d %H:%M:%S")
n_date = datetime.datetime.now()
absdiff = abs(n_date - c_obj_date)
hours = (absdiff.days * 24 * 60 * 60 + absdiff.seconds) / 3600.0
return hours
def job_management(write=False, job=None, last_run_completed=None, current_run=None, status=None):
jobresults = []
#import db
myDB = db.DBConnection()
if job is None:
dbupdate_newstatus = 'Waiting'
dbupdate_nextrun = None
if mylar.CONFIG.ENABLE_RSS is True:
rss_newstatus = 'Waiting'
else:
rss_newstatus = 'Paused'
rss_nextrun = None
weekly_newstatus = 'Waiting'
weekly_nextrun = None
search_newstatus = 'Waiting'
search_nextrun = None
version_newstatus = 'Waiting'
version_nextrun = None
if mylar.CONFIG.ENABLE_CHECK_FOLDER is True:
monitor_newstatus = 'Waiting'
else:
monitor_newstatus = 'Paused'
monitor_nextrun = None
job_info = myDB.select('SELECT DISTINCT * FROM jobhistory')
#set default values if nothing has been ran yet
for ji in job_info:
if 'update' in ji['JobName'].lower():
if mylar.SCHED_DBUPDATE_LAST is None:
mylar.SCHED_DBUPDATE_LAST = ji['prev_run_timestamp']
dbupdate_newstatus = ji['status']
mylar.UPDATER_STATUS = dbupdate_newstatus
dbupdate_nextrun = ji['next_run_timestamp']
elif 'search' in ji['JobName'].lower():
if mylar.SCHED_SEARCH_LAST is None:
mylar.SCHED_SEARCH_LAST = ji['prev_run_timestamp']
search_newstatus = ji['status']
mylar.SEARCH_STATUS = search_newstatus
search_nextrun = ji['next_run_timestamp']
elif 'rss' in ji['JobName'].lower():
if mylar.SCHED_RSS_LAST is None:
mylar.SCHED_RSS_LAST = ji['prev_run_timestamp']
rss_newstatus = ji['status']
mylar.RSS_STATUS = rss_newstatus
rss_nextrun = ji['next_run_timestamp']
elif 'weekly' in ji['JobName'].lower():
if mylar.SCHED_WEEKLY_LAST is None:
mylar.SCHED_WEEKLY_LAST = ji['prev_run_timestamp']
weekly_newstatus = ji['status']
mylar.WEEKLY_STATUS = weekly_newstatus
weekly_nextrun = ji['next_run_timestamp']
elif 'version' in ji['JobName'].lower():
if mylar.SCHED_VERSION_LAST is None:
mylar.SCHED_VERSION_LAST = ji['prev_run_timestamp']
version_newstatus = ji['status']
mylar.VERSION_STATUS = version_newstatus
version_nextrun = ji['next_run_timestamp']
elif 'monitor' in ji['JobName'].lower():
if mylar.SCHED_MONITOR_LAST is None:
mylar.SCHED_MONITOR_LAST = ji['prev_run_timestamp']
monitor_newstatus = ji['status']
mylar.MONITOR_STATUS = monitor_newstatus
monitor_nextrun = ji['next_run_timestamp']
monitors = {'weekly': mylar.SCHED_WEEKLY_LAST,
'monitor': mylar.SCHED_MONITOR_LAST,
'search': mylar.SCHED_SEARCH_LAST,
'dbupdater': mylar.SCHED_DBUPDATE_LAST,
'version': mylar.SCHED_VERSION_LAST,
'rss': mylar.SCHED_RSS_LAST}
#this is for initial startup
for jb in mylar.SCHED.get_jobs():
#logger.fdebug('jb: %s' % jb)
jobinfo = str(jb)
if 'Status Updater' in jobinfo.lower():
continue
elif 'update' in jobinfo.lower():
prev_run_timestamp = mylar.SCHED_DBUPDATE_LAST
newstatus = dbupdate_newstatus
mylar.UPDATER_STATUS = newstatus
elif 'search' in jobinfo.lower():
prev_run_timestamp = mylar.SCHED_SEARCH_LAST
newstatus = search_newstatus
mylar.SEARCH_STATUS = newstatus
elif 'rss' in jobinfo.lower():
prev_run_timestamp = mylar.SCHED_RSS_LAST
newstatus = rss_newstatus
mylar.RSS_STATUS = newstatus
elif 'weekly' in jobinfo.lower():
prev_run_timestamp = mylar.SCHED_WEEKLY_LAST
newstatus = weekly_newstatus
mylar.WEEKLY_STATUS = newstatus
elif 'version' in jobinfo.lower():
prev_run_timestamp = mylar.SCHED_VERSION_LAST
newstatus = version_newstatus
mylar.VERSION_STATUS = newstatus
elif 'monitor' in jobinfo.lower():
prev_run_timestamp = mylar.SCHED_MONITOR_LAST
newstatus = monitor_newstatus
mylar.MONITOR_STATUS = newstatus
jobname = jobinfo[:jobinfo.find('(')-1].strip()
#logger.fdebug('jobinfo: %s' % jobinfo)
try:
jobtimetmp = jobinfo.split('at: ')[1].split('.')[0].strip()
except:
continue
#logger.fdebug('jobtimetmp: %s' % jobtimetmp)
jobtime = float(calendar.timegm(datetime.datetime.strptime(jobtimetmp[:-1], '%Y-%m-%d %H:%M:%S %Z').timetuple()))
#logger.fdebug('jobtime: %s' % jobtime)
if prev_run_timestamp is not None:
prev_run_time_utc = datetime.datetime.utcfromtimestamp(float(prev_run_timestamp))
prev_run_time_utc = prev_run_time_utc.replace(microsecond=0)
else:
prev_run_time_utc = None
#logger.fdebug('prev_run_time: %s' % prev_run_timestamp)
#logger.fdebug('prev_run_time type: %s' % type(prev_run_timestamp))
jobresults.append({'jobname': jobname,
'next_run_datetime': datetime.datetime.utcfromtimestamp(jobtime),
'prev_run_datetime': prev_run_time_utc,
'next_run_timestamp': jobtime,
'prev_run_timestamp': prev_run_timestamp,
'status': newstatus})
if not write:
if len(jobresults) == 0:
return monitors
else:
return jobresults
else:
if job is None:
for x in jobresults:
updateCtrl = {'JobName': x['jobname']}
updateVals = {'next_run_timestamp': x['next_run_timestamp'],
'prev_run_timestamp': x['prev_run_timestamp'],
'next_run_datetime': x['next_run_datetime'],
'prev_run_datetime': x['prev_run_datetime'],
'status': x['status']}
myDB.upsert('jobhistory', updateVals, updateCtrl)
else:
#logger.fdebug('Updating info - job: %s' % job)
#logger.fdebug('Updating info - last run: %s' % last_run_completed)
#logger.fdebug('Updating info - status: %s' % status)
updateCtrl = {'JobName': job}
if current_run is not None:
pr_datetime = datetime.datetime.utcfromtimestamp(current_run)
pr_datetime = pr_datetime.replace(microsecond=0)
updateVals = {'prev_run_timestamp': current_run,
'prev_run_datetime': pr_datetime,
'status': status}
#logger.info('updateVals: %s' % updateVals)
elif last_run_completed is not None:
if any([job == 'DB Updater', job == 'Auto-Search', job == 'RSS Feeds', job == 'Weekly Pullist', job == 'Check Version', job == 'Folder Monitor']):
jobstore = None
for jbst in mylar.SCHED.get_jobs():
jb = str(jbst)
if 'Status Updater' in jb.lower():
continue
elif job == 'DB Updater' and 'update' in jb.lower():
nextrun_stamp = utctimestamp() + (int(mylar.DBUPDATE_INTERVAL) * 60)
jobstore = jbst
break
elif job == 'Auto-Search' and 'search' in jb.lower():
nextrun_stamp = utctimestamp() + (mylar.CONFIG.SEARCH_INTERVAL * 60)
jobstore = jbst
break
elif job == 'RSS Feeds' and 'rss' in jb.lower():
nextrun_stamp = utctimestamp() + (int(mylar.CONFIG.RSS_CHECKINTERVAL) * 60)
mylar.SCHED_RSS_LAST = last_run_completed
jobstore = jbst
break
elif job == 'Weekly Pullist' and 'weekly' in jb.lower():
if mylar.CONFIG.ALT_PULL == 2:
wkt = 4
else:
wkt = 24
nextrun_stamp = utctimestamp() + (wkt * 60 * 60)
mylar.SCHED_WEEKLY_LAST = last_run_completed
jobstore = jbst
break
elif job == 'Check Version' and 'version' in jb.lower():
nextrun_stamp = utctimestamp() + (mylar.CONFIG.CHECK_GITHUB_INTERVAL * 60)
jobstore = jbst
break
elif job == 'Folder Monitor' and 'monitor' in jb.lower():
nextrun_stamp = utctimestamp() + (int(mylar.CONFIG.DOWNLOAD_SCAN_INTERVAL) * 60)
jobstore = jbst
break
if jobstore is not None:
nextrun_date = datetime.datetime.utcfromtimestamp(nextrun_stamp)
jobstore.modify(next_run_time=nextrun_date)
nextrun_date = nextrun_date.replace(microsecond=0)
else:
# if the rss is enabled after startup, we have to re-set it up...
nextrun_stamp = utctimestamp() + (int(mylar.CONFIG.RSS_CHECKINTERVAL) * 60)
nextrun_date = datetime.datetime.utcfromtimestamp(nextrun_stamp)
mylar.SCHED_RSS_LAST = last_run_completed
logger.fdebug('ReScheduled job: %s to %s' % (job, nextrun_date))
lastrun_comp = datetime.datetime.utcfromtimestamp(last_run_completed)
lastrun_comp = lastrun_comp.replace(microsecond=0)
#if it's completed, then update the last run time to the ending time of the job
updateVals = {'prev_run_timestamp': last_run_completed,
'prev_run_datetime': lastrun_comp,
'last_run_completed': 'True',
'next_run_timestamp': nextrun_stamp,
'next_run_datetime': nextrun_date,
'status': status}
#logger.fdebug('Job update for %s: %s' % (updateCtrl, updateVals))
myDB.upsert('jobhistory', updateVals, updateCtrl)
def stupidchk():
#import db
myDB = db.DBConnection()
CCOMICS = myDB.select("SELECT COUNT(*) FROM comics WHERE Status='Active'")
ens = myDB.select("SELECT COUNT(*) FROM comics WHERE Status='Loading' OR Status='Paused'")
mylar.COUNT_COMICS = CCOMICS[0][0]
mylar.EN_OOMICS = ens[0][0]
def newznab_test(name, host, ssl, apikey):
from xml.dom.minidom import parseString, Element
params = {'t': 'search',
'apikey': apikey,
'o': 'xml'}
if host[:-1] == '/':
host = host + 'api'
else:
host = host + '/api'
headers = {'User-Agent': str(mylar.USER_AGENT)}
logger.info('host: %s' % host)
try:
r = requests.get(host, params=params, headers=headers, verify=bool(ssl))
except Exception as e:
logger.warn('Unable to connect: %s' % e)
return
else:
try:
data = parseString(r.content)
except Exception as e:
logger.warn('[WARNING] Error attempting to test: %s' % e)
try:
error_code = data.getElementsByTagName('error')[0].attributes['code'].value
except Exception as e:
logger.info('Connected - Status code returned: %s' % r.status_code)
if r.status_code == 200:
return True
else:
logger.warn('Received response - Status code returned: %s' % r.status_code)
return False
code = error_code
description = data.getElementsByTagName('error')[0].attributes['description'].value
logger.info('[ERROR:%s] - %s' % (code, description))
return False
def torznab_test(name, host, ssl, apikey):
from xml.dom.minidom import parseString, Element
params = {'t': 'search',
'apikey': apikey,
'o': 'xml'}
if host[-1:] == '/':
host = host[:-1]
headers = {'User-Agent': str(mylar.USER_AGENT)}
logger.info('host: %s' % host)
try:
r = requests.get(host, params=params, headers=headers, verify=bool(ssl))
except Exception as e:
logger.warn('Unable to connect: %s' % e)
return
else:
try:
data = parseString(r.content)
except Exception as e:
logger.warn('[WARNING] Error attempting to test: %s' % e)
try:
error_code = data.getElementsByTagName('error')[0].attributes['code'].value
except Exception as e:
logger.info('Connected - Status code returned: %s' % r.status_code)
if r.status_code == 200:
return True
else:
logger.warn('Received response - Status code returned: %s' % r.status_code)
return False
code = error_code
description = data.getElementsByTagName('error')[0].attributes['description'].value
logger.info('[ERROR:%s] - %s' % (code, description))
return False
def get_free_space(folder):
min_threshold = 100000000 #threshold for minimum amount of freespace available (#100mb)
if platform.system() == "Windows":
free_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
dst_freesize = free_bytes.value
else:
st = os.statvfs(folder)
dst_freesize = st.f_bavail * st.f_frsize
logger.fdebug('[FREESPACE-CHECK] %s has %s free' % (folder, sizeof_fmt(dst_freesize)))
if min_threshold > dst_freesize:
logger.warn('[FREESPACE-CHECK] There is only %s space left on %s' % (dst_freesize, folder))
return False
else:
return True
def sizeof_fmt(num, suffix='B'):
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
def getImage(comicid, url, issueid=None):
if os.path.exists(mylar.CONFIG.CACHE_DIR):
pass
else:
#let's make the dir.
try:
os.makedirs(str(mylar.CONFIG.CACHE_DIR))
logger.info('Cache Directory successfully created at: %s' % mylar.CONFIG.CACHE_DIR)
except OSError:
logger.error('Could not create cache dir. Check permissions of cache dir: %s' % mylar.CONFIG.CACHE_DIR)
coverfile = os.path.join(mylar.CONFIG.CACHE_DIR, str(comicid) + '.jpg')
#if cover has '+' in url it's malformed, we need to replace '+' with '%20' to retreive properly.
#new CV API restriction - one api request / second.(probably unecessary here, but it doesn't hurt)
if mylar.CONFIG.CVAPI_RATE is None or mylar.CONFIG.CVAPI_RATE < 2:
time.sleep(2)
else:
time.sleep(mylar.CONFIG.CVAPI_RATE)
logger.info('Attempting to retrieve the comic image for series')
try:
r = requests.get(url, params=None, stream=True, verify=mylar.CONFIG.CV_VERIFY, headers=mylar.CV_HEADERS)
except Exception as e:
logger.warn('[ERROR: %s] Unable to download image from CV URL link: %s' % (e, url))
coversize = 0
statuscode = '400'
else:
statuscode = str(r.status_code)
logger.fdebug('comic image retrieval status code: %s' % statuscode)
if statuscode != '200':
logger.warn('Unable to download image from CV URL link: %s [Status Code returned: %s]' % (url, statuscode))
coversize = 0
else:
if r.headers.get('Content-Encoding') == 'gzip':
buf = StringIO(r.content)
f = gzip.GzipFile(fileobj=buf)
with open(coverfile, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
statinfo = os.stat(coverfile)
coversize = statinfo.st_size
if any([int(coversize) < 10000, statuscode != '200']):
try:
if statuscode != '200':
logger.info('Trying to grab an alternate cover due to problems trying to retrieve the main cover image.')
else:
logger.info('Image size invalid [%s bytes] - trying to get alternate cover image.' % coversize)
except Exception as e:
logger.info('Image size invalid [%s bytes] - trying to get alternate cover image.' % coversize)
logger.fdebug('invalid image link is here: %s' % url)
if os.path.exists(coverfile):
os.remove(coverfile)
return 'retry'
def publisherImages(publisher):
if publisher == 'DC Comics':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-dccomics.png',
'publisher_image_alt': 'DC',
'publisher_imageH': '50',
'publisher_imageW': '50'}
elif publisher == 'Marvel':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-marvel.jpg',
'publisher_image_alt': 'Marvel',
'publisher_imageH': '50',
'publisher_imageW': '100'}
elif publisher == 'Image':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-imagecomics.png',
'publisher_image_alt': 'Image',
'publisher_imageH': '100',
'publisher_imageW': '50'}
elif publisher == 'Dark Horse Comics' or publisher == 'Dark Horse':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-darkhorse.png',
'publisher_image_alt': 'DarkHorse',
'publisher_imageH': '100',
'publisher_imageW': '75'}
elif publisher == 'IDW Publishing':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-idwpublish.png',
'publisher_image_alt': 'IDW',
'publisher_imageH': '50',
'publisher_imageW': '100'}
elif publisher == 'Icon':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-iconcomics.png',
'publisher_image_alt': 'Icon',
'publisher_imageH': '50',
'publisher_imageW': '100'}
elif publisher == 'Red5':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-red5comics.png',
'publisher_image_alt': 'Red5',
'publisher_imageH': '50',
'publisher_imageW': '100'}
elif publisher == 'Vertigo':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-vertigo.png',
'publisher_image_alt': 'Vertigo',
'publisher_imageH': '50',
'publisher_imageW': '100'}
elif publisher == 'Shadowline':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-shadowline.png',
'publisher_image_alt': 'Shadowline',
'publisher_imageH': '50',
'publisher_imageW': '150'}
elif publisher == 'Archie Comics':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-archiecomics.jpg',
'publisher_image_alt': 'Archie',
'publisher_imageH': '75',
'publisher_imageW': '75'}
elif publisher == 'Oni Press':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-onipress.jpg',
'publisher_image_alt': 'Oni Press',
'publisher_imageH': '50',
'publisher_imageW': '100'}
elif publisher == 'Tokyopop':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-tokyopop.jpg',
'publisher_image_alt': 'Tokyopop',
'publisher_imageH': '100',
'publisher_imageW': '50'}
elif publisher == 'Midtown Comics':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-midtowncomics.jpg',
'publisher_image_alt': 'Midtown',
'publisher_imageH': '50',
'publisher_imageW': '100'}
elif publisher == 'Boom! Studios':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-boom.jpg',
'publisher_image_alt': 'Boom!',
'publisher_imageH': '50',
'publisher_imageW': '100'}
elif publisher == 'Skybound':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-skybound.jpg',
'publisher_image_alt': 'Skybound',
'publisher_imageH': '50',
'publisher_imageW': '100'}
elif publisher == 'Dynamite Entertainment':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-dynamite.png',
'publisher_image_alt': 'Dynamite',
'publisher_imageH': '50',
'publisher_imageW': '125'}
elif publisher == 'Top Cow':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-topcow.gif',
'publisher_image_alt': 'Top Cow',
'publisher_imageH': '75',
'publisher_imageW': '100'}
elif publisher == 'Cartoon Books':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-cartoonbooks.jpg',
'publisher_image_alt': 'Cartoon Books',
'publisher_imageH': '75',
'publisher_imageW': '90'}
elif publisher == 'Valiant':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-valiant.png',
'publisher_image_alt': 'Valiant',
'publisher_imageH': '100',
'publisher_imageW': '100'}
elif publisher == 'Action Lab':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-actionlabs.png',
'publisher_image_alt': 'Action Lab',
'publisher_imageH': '100',
'publisher_imageW': '100'}
elif publisher == 'Zenescope Entertainment':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-zenescope.png',
'publisher_image_alt': 'Zenescope',
'publisher_imageH': '125',
'publisher_imageW': '125'}
elif publisher == '2000 ad':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-2000ad.jpg',
'publisher_image_alt': '2000 AD',
'publisher_imageH': '75',
'publisher_imageW': '50'}
elif publisher == 'Aardvark':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-aardvark.png',
'publisher_image_alt': 'Aardvark',
'publisher_imageH': '100',
'publisher_imageW': '100'}
elif publisher == 'Abstract Studio':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-abstract.jpg',
'publisher_image_alt': 'Abstract Studio',
'publisher_imageH': '75',
'publisher_imageW': '50'}
elif publisher == 'Aftershock Comics':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-aftershock.jpg',
'publisher_image_alt': 'Aftershock',
'publisher_imageH': '100',
'publisher_imageW': '75'}
elif publisher == 'Avatar Press':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-avatarpress.jpg',
'publisher_image_alt': 'Avatar Press',
'publisher_imageH': '100',
'publisher_imageW': '75'}
elif publisher == 'Benitez Productions':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-benitez.png',
'publisher_image_alt': 'Benitez',
'publisher_imageH': '75',
'publisher_imageW': '125'}
elif publisher == 'Boundless Comics':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-boundless.png',
'publisher_image_alt': 'Boundless',
'publisher_imageH': '75',
'publisher_imageW': '75'}
elif publisher == 'Darby Pop':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-darbypop.png',
'publisher_image_alt': 'Darby Pop',
'publisher_imageH': '75',
'publisher_imageW': '125'}
elif publisher == 'Devil\'s Due':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-devilsdue.png',
'publisher_image_alt': 'Devil\'s Due',
'publisher_imageH': '75',
'publisher_imageW': '75'}
elif publisher == 'Joe Books':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-joebooks.png',
'publisher_image_alt': 'Joe Books',
'publisher_imageH': '100',
'publisher_imageW': '100'}
elif publisher == 'Titan Comics':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-titan.png',
'publisher_image_alt': 'Titan',
'publisher_imageH': '75',
'publisher_imageW': '75'}
elif publisher == 'Viz':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-viz.png',
'publisher_image_alt': 'Viz',
'publisher_imageH': '50',
'publisher_imageW': '50'}
elif publisher == 'Warp Graphics':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-warpgraphics.png',
'publisher_image_alt': 'Warp Graphics',
'publisher_imageH': '125',
'publisher_imageW': '75'}
elif publisher == 'Wildstorm':
comicpublisher = {'publisher_image': 'interfaces/default/images/publisherlogos/logo-wildstorm.png',
'publisher_image_alt': 'Wildstorm',
'publisher_imageH': '50',
'publisher_imageW': '100'}
else:
comicpublisher = {'publisher_image': None,
'publisher_image_alt': 'Nope',
'publisher_imageH': '0',
'publisher_imageW': '0'}
return comicpublisher
def lookupthebitches(filelist, folder, nzbname, nzbid, prov, hash, pulldate):
#import db
myDB = db.DBConnection()
watchlist = listLibrary()
matchlist = []
#get the weeknumber/year for the pulldate
dt = datetime.datetime.strptime(pulldate, '%Y-%m-%d')
weeknumber = dt.strftime("%U")
year = dt.strftime("%Y")
for f in filelist:
file = re.sub(folder, '', f).strip()
pp = mylar.filechecker.FileChecker(justparse=True, file=file)
parsedinfo = pp.listFiles()
if parsedinfo['parse_status'] == 'success':
dyncheck = re.sub('[\|\s]', '', parsedinfo['dynamic_name'].lower()).strip()
check = myDB.selectone('SELECT * FROM weekly WHERE DynamicName=? AND weeknumber=? AND year=? AND STATUS<>"Downloaded"', [dyncheck, weeknumber, year]).fetchone()
if check is not None:
logger.fdebug('[%s] found match: %s #%s' % (file, check['COMIC'], check['ISSUE']))
matchlist.append({'comicname': check['COMIC'],
'issue': check['ISSUE'],
'comicid': check['ComicID'],
'issueid': check['IssueID'],
'dynamicname': check['DynamicName']})
else:
logger.fdebug('[%s] unable to match to the pull: %s' % (file, parsedinfo))
if len(matchlist) > 0:
for x in matchlist:
if all([x['comicid'] not in watchlist, mylar.CONFIG.PACK_0DAY_WATCHLIST_ONLY is False]):
oneoff = True
mode = 'pullwant'
elif all([x['comicid'] not in watchlist, mylar.CONFIG.PACK_0DAY_WATCHLIST_ONLY is True]):
continue
else:
oneoff = False
mode = 'want'
mylar.updater.nzblog(x['issueid'], nzbname, x['comicname'], id=nzbid, prov=prov, oneoff=oneoff)
mylar.updater.foundsearch(x['comicid'], x['issueid'], mode=mode, provider=prov, hash=hash)
def DateAddedFix():
#import db
myDB = db.DBConnection()
DA_A = datetime.datetime.today()
DateAdded = DA_A.strftime('%Y-%m-%d')
issues = myDB.select("SELECT IssueID FROM issues WHERE Status='Wanted' and DateAdded is NULL")
for da in issues:
myDB.upsert("issues", {'DateAdded': DateAdded}, {'IssueID': da[0]})
annuals = myDB.select("SELECT IssueID FROM annuals WHERE Status='Wanted' and DateAdded is NULL")
for an in annuals:
myDB.upsert("annuals", {'DateAdded': DateAdded}, {'IssueID': an[0]})
def file_ops(path,dst,arc=False,one_off=False):
# # path = source path + filename
# # dst = destination path + filename
# # arc = to denote if the file_operation is being performed as part of a story arc or not where the series exists on the watchlist already
# # one-off = if the file_operation is being performed where it is either going into the grabbab_dst or story arc folder
# #get the crc of the file prior to the operation and then compare after to ensure it's complete.
# crc_check = mylar.filechecker.crc(path)
# #will be either copy / move
if any([one_off, arc]):
action_op = mylar.CONFIG.ARC_FILEOPS
else:
action_op = mylar.CONFIG.FILE_OPTS
if action_op == 'copy' or (arc is True and any([action_op == 'copy', action_op == 'move'])):
try:
shutil.copy( path , dst )
# if crc_check == mylar.filechecker.crc(dst):
except Exception as e:
logger.error('[%s] error : %s' % (action_op, e))
return False
return True
elif action_op == 'move':
try:
shutil.move( path , dst )
# if crc_check == mylar.filechecker.crc(dst):
except Exception as e:
logger.error('[MOVE] error : %s' % e)
return False
return True
elif any([action_op == 'hardlink', action_op == 'softlink']):
if 'windows' not in mylar.OS_DETECT.lower():
# if it's an arc, then in needs to go reverse since we want to keep the src files (in the series directory)
if action_op == 'hardlink':
import sys
# Open a file
try:
fd = os.open( path, os.O_RDWR|os.O_CREAT )
os.close( fd )
# Now create another copy of the above file.
os.link( path, dst )
logger.info('Created hard link successfully!!')
except OSError, e:
if e.errno == errno.EXDEV:
logger.warn('[' + str(e) + '] Hardlinking failure. Could not create hardlink - dropping down to copy mode so that this operation can complete. Intervention is required if you wish to continue using hardlinks.')
try:
shutil.copy( path, dst )
logger.fdebug('Successfully copied file to : ' + dst)
return True
except Exception as e:
logger.error('[COPY] error : %s' % e)
return False
else:
logger.warn('[' + str(e) + '] Hardlinking failure. Could not create hardlink - Intervention is required if you wish to continue using hardlinks.')
return False
hardlinks = os.lstat( dst ).st_nlink
if hardlinks > 1:
logger.info('Created hard link [' + str(hardlinks) + '] successfully!! (' + dst + ')')
else:
logger.warn('Hardlink cannot be verified. You should probably verify that it is created properly.')
return True
elif action_op == 'softlink':
try:
#first we need to copy the file to the new location, then create the symlink pointing from new -> original
if not arc:
shutil.move( path, dst )
if os.path.lexists( path ):
os.remove( path )
os.symlink( dst, path )
logger.fdebug('Successfully created softlink [' + dst + ' --> ' + path + ']')
else:
os.symlink ( path, dst )
logger.fdebug('Successfully created softlink [' + path + ' --> ' + dst + ']')
except OSError, e:
#if e.errno == errno.EEXIST:
# os.remove(dst)
# os.symlink( path, dst )
#else:
logger.warn('[' + str(e) + '] Unable to create symlink. Dropping down to copy mode so that this operation can continue.')
try:
shutil.copy( dst, path )
logger.fdebug('Successfully copied file [' + dst + ' --> ' + path + ']')
except Exception as e:
logger.error('[COPY] error : %s' % e)
return False
return True
else:
#Not ready just yet.
pass
#softlinks = shortcut (normally junctions are called softlinks, but for this it's being called a softlink)
#hardlinks = MUST reside on the same drive as the original
#junctions = not used (for directories across same machine only but different drives)
#option 1
#this one needs to get tested
#import ctypes
#kdll = ctypes.windll.LoadLibrary("kernel32.dll")
#kdll.CreateSymbolicLinkW(path, dst, 0)
#option 2
import lib.winlink as winlink
if mylar.CONFIG.FILE_OPTS == 'hardlink':
try:
os.system(r'mklink /H dst path')
logger.fdebug('Successfully hardlinked file [' + dst + ' --> ' + path + ']')
except OSError, e:
logger.warn('[' + e + '] Unable to create symlink. Dropping down to copy mode so that this operation can continue.')
try:
shutil.copy( dst, path )
logger.fdebug('Successfully copied file [' + dst + ' --> ' + path + ']')
except:
return False
elif mylar.CONFIG.FILE_OPTS == 'softlink': #ie. shortcut.
try:
shutil.move( path, dst )
if os.path.lexists( path ):
os.remove( path )
os.system(r'mklink dst path')
logger.fdebug('Successfully created symlink [' + dst + ' --> ' + path + ']')
except OSError, e:
raise e
logger.warn('[' + e + '] Unable to create softlink. Dropping down to copy mode so that this operation can continue.')
try:
shutil.copy( dst, path )
logger.fdebug('Successfully copied file [' + dst + ' --> ' + path + ']')
except:
return False
else:
return False
from threading import Thread
class ThreadWithReturnValue(Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, Verbose=None):
Thread.__init__(self, group, target, name, args, kwargs, Verbose)
self._return = None
def run(self):
if self._Thread__target is not None:
self._return = self._Thread__target(*self._Thread__args, **self._Thread__kwargs)
def join(self):
Thread.join(self)
return self._return
| 191,351 | Python | .py | 3,716 | 37.050054 | 335 | 0.528789 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,269 | PostProcessor.py | evilhero_mylar/mylar/PostProcessor.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from __future__ import with_statement
import os
import shutil
import datetime
import re
import shlex
import time
import logging
import mylar
import subprocess
import urllib2
import sys
from xml.dom.minidom import parseString
from mylar import logger, db, helpers, updater, notifiers, filechecker, weeklypull
class PostProcessor(object):
"""
A class which will process a media file according to the post processing settings in the config.
"""
EXISTS_LARGER = 1
EXISTS_SAME = 2
EXISTS_SMALLER = 3
DOESNT_EXIST = 4
NZB_NAME = 1
FOLDER_NAME = 2
FILE_NAME = 3
def __init__(self, nzb_name, nzb_folder, issueid=None, module=None, queue=None, comicid=None, apicall=False, ddl=False):
"""
Creates a new post processor with the given file path and optionally an NZB name.
file_path: The path to the file to be processed
nzb_name: The name of the NZB which resulted in this file being downloaded (optional)
"""
# name of the NZB that resulted in this folder
self.nzb_name = nzb_name
self.nzb_folder = nzb_folder
if module is not None:
self.module = module + '[POST-PROCESSING]'
else:
self.module = '[POST-PROCESSING]'
if queue:
self.queue = queue
if mylar.APILOCK is True:
return {'status': 'IN PROGRESS'}
if apicall is True:
self.apicall = True
mylar.APILOCK = True
else:
self.apicall = False
if ddl is True:
self.ddl = True
else:
self.ddl = False
if mylar.CONFIG.FILE_OPTS == 'copy':
self.fileop = shutil.copy
else:
self.fileop = shutil.move
self.valreturn = []
self.extensions = ('.cbr', '.cbz', '.pdf')
self.failed_files = 0
self.log = ''
if issueid is not None:
self.issueid = issueid
else:
self.issueid = None
if comicid is not None:
self.comicid = comicid
else:
self.comicid = None
self.issuearcid = None
def _log(self, message, level=logger): #.message): #level=logger.MESSAGE):
"""
A wrapper for the internal logger which also keeps track of messages and saves them to a string for sabnzbd post-processing logging functions.
message: The string to log (unicode)
level: The log level to use (optional)
"""
# logger.log(message, level)
self.log += message + '\n'
def _run_pre_scripts(self, nzb_name, nzb_folder, seriesmetadata):
"""
Executes any pre scripts defined in the config.
ep_obj: The object to use when calling the pre script
"""
logger.fdebug("initiating pre script detection.")
self._log("initiating pre script detection.")
logger.fdebug("mylar.PRE_SCRIPTS : " + mylar.CONFIG.PRE_SCRIPTS)
self._log("mylar.PRE_SCRIPTS : " + mylar.CONFIG.PRE_SCRIPTS)
# for currentScriptName in mylar.CONFIG.PRE_SCRIPTS:
with open(mylar.CONFIG.PRE_SCRIPTS, 'r') as f:
first_line = f.readline()
if mylar.CONFIG.PRE_SCRIPTS.endswith('.sh'):
shell_cmd = re.sub('#!', '', first_line).strip()
if shell_cmd == '' or shell_cmd is None:
shell_cmd = '/bin/bash'
else:
#forces mylar to use the executable that it was run with to run the extra script.
shell_cmd = sys.executable
currentScriptName = shell_cmd + ' ' + str(mylar.CONFIG.PRE_SCRIPTS).decode("string_escape")
logger.fdebug("pre script detected...enabling: " + str(currentScriptName))
# generate a safe command line string to execute the script and provide all the parameters
script_cmd = shlex.split(currentScriptName, posix=False) + [str(nzb_name), str(nzb_folder), str(seriesmetadata)]
logger.fdebug("cmd to be executed: " + str(script_cmd))
self._log("cmd to be executed: " + str(script_cmd))
# use subprocess to run the command and capture output
logger.fdebug(u"Executing command " +str(script_cmd))
logger.fdebug(u"Absolute path to script: " +script_cmd[0])
try:
p = subprocess.Popen(script_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=mylar.PROG_DIR)
out, err = p.communicate() #@UnusedVariable
logger.fdebug(u"Script result: " + out)
self._log(u"Script result: " + out)
except OSError, e:
logger.warn(u"Unable to run pre_script: " + str(script_cmd))
self._log(u"Unable to run pre_script: " + str(script_cmd))
def _run_extra_scripts(self, nzb_name, nzb_folder, filen, folderp, seriesmetadata):
"""
Executes any extra scripts defined in the config.
ep_obj: The object to use when calling the extra script
"""
logger.fdebug("initiating extra script detection.")
self._log("initiating extra script detection.")
logger.fdebug("mylar.EXTRA_SCRIPTS : " + mylar.CONFIG.EXTRA_SCRIPTS)
self._log("mylar.EXTRA_SCRIPTS : " + mylar.CONFIG.EXTRA_SCRIPTS)
# for curScriptName in mylar.CONFIG.EXTRA_SCRIPTS:
with open(mylar.CONFIG.EXTRA_SCRIPTS, 'r') as f:
first_line = f.readline()
if mylar.CONFIG.EXTRA_SCRIPTS.endswith('.sh'):
shell_cmd = re.sub('#!', '', first_line)
if shell_cmd == '' or shell_cmd is None:
shell_cmd = '/bin/bash'
else:
#forces mylar to use the executable that it was run with to run the extra script.
shell_cmd = sys.executable
curScriptName = shell_cmd + ' ' + str(mylar.CONFIG.EXTRA_SCRIPTS).decode("string_escape")
logger.fdebug("extra script detected...enabling: " + str(curScriptName))
# generate a safe command line string to execute the script and provide all the parameters
script_cmd = shlex.split(curScriptName) + [str(nzb_name), str(nzb_folder), str(filen), str(folderp), str(seriesmetadata)]
logger.fdebug("cmd to be executed: " + str(script_cmd))
self._log("cmd to be executed: " + str(script_cmd))
# use subprocess to run the command and capture output
logger.fdebug(u"Executing command " +str(script_cmd))
logger.fdebug(u"Absolute path to script: " +script_cmd[0])
try:
p = subprocess.Popen(script_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=mylar.PROG_DIR)
out, err = p.communicate() #@UnusedVariable
logger.fdebug(u"Script result: " + out)
self._log(u"Script result: " + out)
except OSError, e:
logger.warn(u"Unable to run extra_script: " + str(script_cmd))
self._log(u"Unable to run extra_script: " + str(script_cmd))
def duplicate_process(self, dupeinfo):
#path to move 'should' be the entire path to the given file
path_to_move = dupeinfo['to_dupe']
file_to_move = os.path.split(path_to_move)[1]
if dupeinfo['action'] == 'dupe_src' and mylar.CONFIG.FILE_OPTS == 'move':
logger.info('[DUPLICATE-CLEANUP] New File will be post-processed. Moving duplicate [%s] to Duplicate Dump Folder for manual intervention.' % path_to_move)
else:
if mylar.CONFIG.FILE_OPTS == 'move':
logger.info('[DUPLICATE-CLEANUP][MOVE-MODE] New File will not be post-processed. Moving duplicate [%s] to Duplicate Dump Folder for manual intervention.' % path_to_move)
else:
logger.info('[DUPLICATE-CLEANUP][COPY-MODE] NEW File will not be post-processed. Retaining file in original location [%s]' % path_to_move)
return True
#this gets tricky depending on if it's the new filename or the existing filename, and whether or not 'copy' or 'move' has been selected.
if mylar.CONFIG.FILE_OPTS == 'move':
#check to make sure duplicate_dump directory exists:
checkdirectory = filechecker.validateAndCreateDirectory(mylar.CONFIG.DUPLICATE_DUMP, True, module='[DUPLICATE-CLEANUP]')
if mylar.CONFIG.DUPLICATE_DATED_FOLDERS is True:
todaydate = datetime.datetime.now().strftime("%Y-%m-%d")
dump_folder = os.path.join(mylar.CONFIG.DUPLICATE_DUMP, todaydate)
checkdirectory = filechecker.validateAndCreateDirectory(dump_folder, True, module='[DUPLICATE-DATED CLEANUP]')
else:
dump_folder = mylar.CONFIG.DUPLICATE_DUMP
try:
shutil.move(path_to_move, os.path.join(dump_folder, file_to_move))
except (OSError, IOError):
logger.warn('[DUPLICATE-CLEANUP] Failed to move %s ... to ... %s' % (path_to_move, os.path.join(dump_folder, file_to_move)))
return False
logger.warn('[DUPLICATE-CLEANUP] Successfully moved %s ... to ... %s' % (path_to_move, os.path.join(dump_folder, file_to_move)))
return True
def tidyup(self, odir=None, del_nzbdir=False, sub_path=None, cacheonly=False, filename=None):
# del_nzbdir will remove the original directory location. Must be set to False for manual pp or else will delete manual dir that's provided (if empty).
# move = cleanup/delete original location (self.nzb_folder) AND cache location (odir) if metatagging is enabled.
# copy = cleanup/delete cache location (odir) only if enabled.
# cacheonly = will only delete the cache location (useful if there's an error during metatagging, and/or the final location is out of space)
try:
#tidyup old path
if cacheonly is False:
logger.fdebug('File Option: %s [META-ENABLED: %s]' % (mylar.CONFIG.FILE_OPTS, mylar.CONFIG.ENABLE_META))
logger.fdebug('odir: %s [filename: %s][self.nzb_folder: %s]' % (odir, filename, self.nzb_folder))
logger.fdebug('sub_path: %s [cacheonly: %s][del_nzbdir: %s]' % (sub_path, cacheonly, del_nzbdir))
#if sub_path exists, then we need to use that in place of self.nzb_folder since the file was in a sub-directory within self.nzb_folder
if all([sub_path is not None, sub_path != self.nzb_folder]): #, self.issueid is not None]):
if self.issueid is None:
logger.fdebug('Sub-directory detected during cleanup. Will attempt to remove if empty: %s' % sub_path)
orig_folder = sub_path
else:
logger.fdebug('Direct post-processing was performed against specific issueid. Using supplied filepath for deletion.')
orig_folder = self.nzb_folder
else:
orig_folder = self.nzb_folder
#make sure we don't delete the directory passed via manual-pp and ajust for trailling slashes or not
if orig_folder.endswith('/') or orig_folder.endswith('\\'):
tmp_folder = orig_folder[:-1]
else:
tmp_folder = orig_folder
if os.path.split(tmp_folder)[1] == filename and not os.path.isdir(tmp_folder):
logger.fdebug('%s item to be deleted is file, not folder due to direct submission: %s' % (self.module, tmp_folder))
tmp_folder = os.path.split(tmp_folder)[0]
#if all([os.path.isdir(odir), self.nzb_folder != tmp_folder]) or any([odir.startswith('mylar_'),del_nzbdir is True]):
# check to see if the directory is empty or not.
if all([mylar.CONFIG.FILE_OPTS == 'move', self.nzb_name == 'Manual Run', tmp_folder != self.nzb_folder]):
if not os.listdir(tmp_folder):
logger.fdebug('%s Tidying up. Deleting sub-folder location : %s' % (self.module, tmp_folder))
shutil.rmtree(tmp_folder)
self._log("Removed temporary directory : %s" % tmp_folder)
else:
if filename is not None:
if os.path.isfile(os.path.join(tmp_folder,filename)):
logger.fdebug('%s Attempting to remove file: %s' % (self.module, os.path.join(tmp_folder, filename)))
try:
os.remove(os.path.join(tmp_folder, filename))
except Exception as e:
logger.warn('%s [%s] Unable to remove file : %s' % (self.module, e, os.path.join(tmp_folder, filename)))
else:
if not os.listdir(tmp_folder):
logger.fdebug('%s Tidying up. Deleting original folder location : %s' % (self.module, tmp_folder))
try:
shutil.rmtree(tmp_folder)
except Exception as e:
logger.warn('%s [%s] Unable to delete original folder location: %s' % (self.module, e, tmp_folder))
else:
logger.fdebug('%s Removed original folder location: %s' % (self.module, tmp_folder))
self._log("Removed temporary directory : %s" % tmp_folder)
else:
self._log('Failed to remove temporary directory: %s' % tmp_folder)
logger.error('%s %s not empty. Skipping removal of directory - this will either be caught in further post-processing or it will have to be manually deleted.' % (self.module, tmp_folder))
else:
self._log('Failed to remove temporary directory: ' + tmp_folder)
logger.error('%s %s not empty. Skipping removal of directory - this will either be caught in further post-processing or it will have to be manually deleted.' % (self.module, tmp_folder))
elif all([mylar.CONFIG.FILE_OPTS == 'move', self.nzb_name == 'Manual Run', filename is not None]):
if os.path.isfile(os.path.join(tmp_folder,filename)):
logger.fdebug('%s Attempting to remove original file: %s' % (self.module, os.path.join(tmp_folder, filename)))
try:
os.remove(os.path.join(tmp_folder, filename))
except Exception as e:
logger.warn('%s [%s] Unable to remove file : %s' % (self.module, e, os.path.join(tmp_folder, filename)))
elif mylar.CONFIG.FILE_OPTS == 'move' and all([del_nzbdir is True, self.nzb_name != 'Manual Run']): #tmp_folder != self.nzb_folder]):
if not os.listdir(tmp_folder):
logger.fdebug('%s Tidying up. Deleting original folder location : %s' % (self.module, tmp_folder))
shutil.rmtree(tmp_folder)
self._log("Removed temporary directory : %s" % tmp_folder)
else:
if filename is not None:
if os.path.isfile(os.path.join(tmp_folder,filename)):
logger.fdebug('%s Attempting to remove file: %s' % (self.module, os.path.join(tmp_folder, filename)))
try:
os.remove(os.path.join(tmp_folder, filename))
except Exception as e:
logger.warn('%s [%s] Unable to remove file : %s' % (self.module, e, os.path.join(tmp_folder, filename)))
else:
if not os.listdir(tmp_folder):
logger.fdebug('%s Tidying up. Deleting original folder location : %s' % (self.module, tmp_folder))
try:
shutil.rmtree(tmp_folder)
except Exception as e:
logger.warn('%s [%s] Unable to delete original folder location: %s' % (self.module, e, tmp_folder))
else:
logger.fdebug('%s Removed original folder location: %s' % (self.module, tmp_folder))
self._log("Removed temporary directory : " + tmp_folder)
else:
self._log('Failed to remove temporary directory: ' + tmp_folder)
logger.error('%s %s not empty. Skipping removal of directory - this will either be caught in further post-processing or it will have to be manually deleted.' % (self.module, tmp_folder))
else:
self._log('Failed to remove temporary directory: ' + tmp_folder)
logger.error('%s %s not empty. Skipping removal of directory - this will either be caught in further post-processing or it will have to be manually deleted.' % (self.module, tmp_folder))
if mylar.CONFIG.ENABLE_META and all([os.path.isdir(odir), 'mylar_' in odir]):
#Regardless of the copy/move operation, we need to delete the files from within the cache directory, then remove the cache directory itself for the given issue.
#sometimes during a meta, it retains the cbr as well after conversion depending on settings. Make sure to delete too thus the 'walk'.
for filename in os.listdir(odir):
filepath = os.path.join(odir, filename)
try:
os.remove(filepath)
except OSError:
pass
if not os.listdir(odir):
logger.fdebug('%s Tidying up. Deleting temporary cache directory : %s' % (self.module, odir))
shutil.rmtree(odir)
self._log("Removed temporary directory : %s" % odir)
else:
self._log('Failed to remove temporary directory: %s' % odir)
logger.error('%s %s not empty. Skipping removal of temporary cache directory - this will either be caught in further post-processing or have to be manually deleted.' % (self.module, odir))
except (OSError, IOError):
logger.fdebug('%s Failed to remove directory - Processing will continue, but manual removal is necessary' % self.module)
self._log('Failed to remove temporary directory')
def Process(self):
module = self.module
self._log('nzb name: %s' % self.nzb_name)
self._log('nzb folder: %s' % self.nzb_folder)
logger.fdebug('%s nzb name: %s' % (module, self.nzb_name))
logger.fdebug('%s nzb folder: %s' % (module, self.nzb_folder))
if self.ddl is False:
if mylar.USE_SABNZBD==1:
if self.nzb_name != 'Manual Run':
logger.fdebug('%s Using SABnzbd' % module)
logger.fdebug('%s NZB name as passed from SABnzbd: %s' % (module, self.nzb_name))
if self.nzb_name == 'Manual Run':
logger.fdebug('%s Manual Run Post-Processing enabled.' % module)
else:
# if the SAB Directory option is enabled, let's use that folder name and append the jobname.
if all([mylar.CONFIG.SAB_TO_MYLAR, mylar.CONFIG.SAB_DIRECTORY is not None, mylar.CONFIG.SAB_DIRECTORY != 'None']):
self.nzb_folder = os.path.join(mylar.CONFIG.SAB_DIRECTORY, self.nzb_name).encode(mylar.SYS_ENCODING)
logger.fdebug('%s SABnzbd Download folder option enabled. Directory set to : %s' % (module, self.nzb_folder))
if mylar.USE_NZBGET==1:
if self.nzb_name != 'Manual Run':
logger.fdebug('%s Using NZBGET' % module)
logger.fdebug('%s NZB name as passed from NZBGet: %s' % (module, self.nzb_name))
# if the NZBGet Directory option is enabled, let's use that folder name and append the jobname.
if self.nzb_name == 'Manual Run':
logger.fdebug('%s Manual Run Post-Processing enabled.' % module)
elif all([mylar.CONFIG.NZBGET_DIRECTORY is not None, mylar.CONFIG.NZBGET_DIRECTORY is not 'None']):
logger.fdebug('%s NZB name as passed from NZBGet: %s' % (module, self.nzb_name))
self.nzb_folder = os.path.join(mylar.CONFIG.NZBGET_DIRECTORY, self.nzb_name).encode(mylar.SYS_ENCODING)
logger.fdebug('%s NZBGET Download folder option enabled. Directory set to : %s' % (module, self.nzb_folder))
else:
logger.fdebug('%s Now performing post-processing of %s sent from DDL' % (module, self.nzb_name))
myDB = db.DBConnection()
self.oneoffinlist = False
if any([self.nzb_name == 'Manual Run', self.issueid is not None, self.comicid is not None, self.apicall is True]):
if all([self.issueid is None, self.comicid is not None, self.apicall is True]) or self.nzb_name == 'Manual Run' or all([self.apicall is True, self.comicid is None, self.issueid is None, self.nzb_name.startswith('0-Day')]):
if self.comicid is not None:
logger.fdebug('%s Now post-processing pack directly against ComicID: %s' % (module, self.comicid))
elif all([self.apicall is True, self.issueid is None, self.comicid is None, self.nzb_name.startswith('0-Day')]):
logger.fdebug('%s Now post-processing 0-day pack: %s' % (module, self.nzb_name))
else:
logger.fdebug('%s Manual Run initiated' % module)
#Manual postprocessing on a folder.
#first we get a parsed results list of the files being processed, and then poll against the sql to get a short list of hits.
flc = filechecker.FileChecker(self.nzb_folder, justparse=True, pp_mode=True)
filelist = flc.listFiles()
if filelist['comiccount'] == 0: # is None:
logger.warn('There were no files located - check the debugging logs if you think this is in error.')
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
logger.info('I have located %s files that I should be able to post-process. Continuing...' % filelist['comiccount'])
else:
if all([self.comicid is None, '_' not in self.issueid]):
cid = myDB.selectone('SELECT ComicID FROM issues where IssueID=?', [str(self.issueid)]).fetchone()
self.comicid = cid[0]
else:
if '_' in self.issueid:
logger.fdebug('Story Arc post-processing request detected.')
self.issuearcid = self.issueid
self.issueid = None
logger.fdebug('%s Now post-processing directly against StoryArcs - ComicID: %s / IssueArcID: %s' % (module, self.comicid, self.issuearcid))
if self.issueid is not None:
logger.fdebug('%s Now post-processing directly against ComicID: %s / IssueID: %s' % (module, self.comicid, self.issueid))
if self.issuearcid is None:
if self.nzb_name.lower().endswith(self.extensions):
flc = filechecker.FileChecker(self.nzb_folder, file=self.nzb_name, pp_mode=True)
fl = flc.listFiles()
filelist = {}
filelist['comiclist'] = [fl]
filelist['comiccount'] = len(filelist['comiclist'])
else:
flc = filechecker.FileChecker(self.nzb_folder, justparse=True, pp_mode=True)
filelist = flc.listFiles()
else:
filelist = {}
filelist['comiclist'] = []
filelist['comiccount'] = 0
#preload the entire ALT list in here.
alt_list = []
alt_db = myDB.select("SELECT * FROM Comics WHERE AlternateSearch != 'None'")
if alt_db is not None:
for aldb in alt_db:
as_d = filechecker.FileChecker(AlternateSearch=helpers.conversion(aldb['AlternateSearch']))
as_dinfo = as_d.altcheck()
alt_list.append({'AS_Alt': as_dinfo['AS_Alt'],
'AS_Tuple': as_dinfo['AS_Tuple'],
'AS_DyComicName': aldb['DynamicComicName']})
manual_arclist = []
oneoff_issuelist = []
manual_list = []
for fl in filelist['comiclist']:
self.matched = False
as_d = filechecker.FileChecker()
as_dinfo = as_d.dynamic_replace(helpers.conversion(fl['series_name']))
orig_seriesname = as_dinfo['mod_seriesname']
mod_seriesname = as_dinfo['mod_seriesname']
loopchk = []
if fl['alt_series'] is not None:
logger.fdebug('%s Alternate series naming detected: %s' % (module, fl['alt_series']))
as_sinfo = as_d.dynamic_replace(helpers.conversion(fl['alt_series']))
mod_altseriesname = as_sinfo['mod_seriesname']
if all([mylar.CONFIG.ANNUALS_ON, 'annual' in mod_altseriesname.lower()]) or all([mylar.CONFIG.ANNUALS_ON, 'special' in mod_altseriesname.lower()]):
mod_altseriesname = re.sub('annual', '', mod_altseriesname, flags=re.I).strip()
mod_altseriesname = re.sub('special', '', mod_altseriesname, flags=re.I).strip()
if not any(re.sub('[\|\s]', '', mod_altseriesname).lower() == x for x in loopchk):
loopchk.append(re.sub('[\|\s]', '', mod_altseriesname.lower()))
for x in alt_list:
cname = x['AS_DyComicName']
for ab in x['AS_Alt']:
tmp_ab = re.sub(' ', '', ab)
tmp_mod_seriesname = re.sub(' ', '', mod_seriesname)
if re.sub('\|', '', tmp_mod_seriesname.lower()).strip() == re.sub('\|', '', tmp_ab.lower()).strip():
if not any(re.sub('[\|\s]', '', cname.lower()) == x for x in loopchk):
loopchk.append(re.sub('[\|\s]', '', cname.lower()))
if all([mylar.CONFIG.ANNUALS_ON, 'annual' in mod_seriesname.lower()]) or all([mylar.CONFIG.ANNUALS_ON, 'special' in mod_seriesname.lower()]):
mod_seriesname = re.sub('annual', '', mod_seriesname, flags=re.I).strip()
mod_seriesname = re.sub('special', '', mod_seriesname, flags=re.I).strip()
#make sure we add back in the original parsed filename here.
if not any(re.sub('[\|\s]', '', mod_seriesname).lower() == x for x in loopchk):
loopchk.append(re.sub('[\|\s]', '', mod_seriesname.lower()))
if any([self.issueid is not None, self.comicid is not None]):
comicseries = myDB.select('SELECT * FROM comics WHERE ComicID=?', [self.comicid])
else:
if fl['issueid'] is not None:
logger.info('issueid detected in filename: %s' % fl['issueid'])
csi = myDB.selectone('SELECT i.ComicID, i.IssueID, i.Issue_Number, c.ComicName FROM comics as c JOIN issues as i ON c.ComicID = i.ComicID WHERE i.IssueID=?', [fl['issueid']]).fetchone()
if csi is None:
csi = myDB.selectone('SELECT i.ComicID as comicid, i.IssueID, i.Issue_Number, a.ReleaseComicName, c.ComicName FROM comics as c JOIN annuals as a ON c.ComicID = a.ComicID WHERE a.IssueID=?', [fl['issueid']]).fetchone()
if csi is not None:
annchk = 'yes'
else:
continue
else:
annchk = 'no'
if fl['sub']:
logger.fdebug('%s[SUB: %s][CLOCATION: %s]' % (module, fl['sub'], fl['comiclocation']))
clocation = os.path.join(fl['comiclocation'], fl['sub'], helpers.conversion(fl['comicfilename']))
else:
logger.fdebug('%s[CLOCATION] %s' % (module, fl['comiclocation']))
clocation = os.path.join(fl['comiclocation'],helpers.conversion(fl['comicfilename']))
annualtype = None
if annchk == 'yes':
if 'Annual' in csi['ReleaseComicName']:
annualtype = 'Annual'
elif 'Special' in csi['ReleaseComicName']:
annualtype = 'Special'
else:
if 'Annual' in csi['ComicName']:
annualtype = 'Annual'
elif 'Special' in csi['ComicName']:
annualtype = 'Special'
manual_list.append({"ComicLocation": clocation,
"ComicID": csi['ComicID'],
"IssueID": csi['IssueID'],
"IssueNumber": csi['Issue_Number'],
"AnnualType": annualtype,
"ComicName": csi['ComicName'],
"Series": fl['series_name'],
"AltSeries": fl['alt_series'],
"One-Off": False,
"ForcedMatch": True})
logger.info('manual_list: %s' % manual_list)
break
else:
tmpsql = "SELECT * FROM comics WHERE DynamicComicName IN ({seq}) COLLATE NOCASE".format(seq=','.join('?' * len(loopchk)))
comicseries = myDB.select(tmpsql, tuple(loopchk))
if not comicseries or orig_seriesname != mod_seriesname:
if all(['special' in orig_seriesname.lower(), mylar.CONFIG.ANNUALS_ON, orig_seriesname != mod_seriesname]):
if not any(re.sub('[\|\s]', '', orig_seriesname).lower() == x for x in loopchk):
loopchk.append(re.sub('[\|\s]', '', orig_seriesname.lower()))
tmpsql = "SELECT * FROM comics WHERE DynamicComicName IN ({seq}) COLLATE NOCASE".format(seq=','.join('?' * len(loopchk)))
comicseries = myDB.select(tmpsql, tuple(loopchk))
#if not comicseries:
# logger.error('[%s][%s] No Series named %s - checking against Story Arcs (just in case). If I do not find anything, maybe you should be running Import?' % (module, fl['comicfilename'], fl['series_name']))
# continue
watchvals = []
for wv in comicseries:
logger.info('Now checking: %s [%s]' % (wv['ComicName'], wv['ComicID']))
#do some extra checks in here to ignore these types:
#check for Paused status /
#check for Ended status and 100% completion of issues.
if wv['Status'] == 'Paused' or (wv['Have'] == wv['Total'] and not any(['Present' in wv['ComicPublished'], helpers.now()[:4] in wv['ComicPublished']])):
logger.warn('%s [%s] is either Paused or in an Ended status with 100%s completion. Ignoring for match.' % (wv['ComicName'], wv['ComicYear'], '%'))
continue
wv_comicname = wv['ComicName']
wv_comicpublisher = wv['ComicPublisher']
wv_alternatesearch = wv['AlternateSearch']
wv_comicid = wv['ComicID']
if (all([wv['Type'] != 'Print', wv['Type'] != 'Digital']) and wv['Corrected_Type'] != 'Print') or wv['Corrected_Type'] == 'TPB':
wv_type = 'TPB'
else:
wv_type = None
wv_seriesyear = wv['ComicYear']
wv_comicversion = wv['ComicVersion']
wv_publisher = wv['ComicPublisher']
wv_total = wv['Total']
if mylar.CONFIG.FOLDER_SCAN_LOG_VERBOSE:
logger.fdebug('Queuing to Check: %s [%s] -- %s' % (wv['ComicName'], wv['ComicYear'], wv['ComicID']))
#force it to use the Publication Date of the latest issue instead of the Latest Date (which could be anything)
latestdate = myDB.select('SELECT IssueDate from issues WHERE ComicID=? order by ReleaseDate DESC', [wv['ComicID']])
if latestdate:
tmplatestdate = latestdate[0][0]
if tmplatestdate[:4] != wv['LatestDate'][:4]:
if tmplatestdate[:4] > wv['LatestDate'][:4]:
latestdate = tmplatestdate
else:
latestdate = wv['LatestDate']
else:
latestdate = tmplatestdate
else:
latestdate = wv['LatestDate']
if latestdate == '0000-00-00' or latestdate == 'None' or latestdate is None:
logger.fdebug('Forcing a refresh of series: %s as it appears to have incomplete issue dates.' % wv_comicname)
updater.dbUpdate([wv_comicid])
logger.fdebug('Refresh complete for %s. Rechecking issue dates for completion.' % wv_comicname)
latestdate = myDB.select('SELECT IssueDate from issues WHERE ComicID=? order by ReleaseDate DESC', [wv['ComicID']])
if latestdate:
tmplatestdate = latestdate[0][0]
if tmplatestdate[:4] != wv['LatestDate'][:4]:
if tmplatestdate[:4] > wv['LatestDate'][:4]:
latestdate = tmplatestdate
else:
latestdate = wv['LatestDate']
else:
latestdate = tmplatestdate
else:
latestdate = wv['LatestDate']
logger.fdebug('Latest Date (after forced refresh) set to :' + str(latestdate))
if latestdate == '0000-00-00' or latestdate == 'None' or latestdate is None:
logger.fdebug('Unable to properly attain the Latest Date for series: %s. Cannot check against this series for post-processing.' % wv_comicname)
continue
watchvals.append({"ComicName": wv_comicname,
"ComicPublisher": wv_comicpublisher,
"AlternateSearch": wv_alternatesearch,
"ComicID": wv_comicid,
"LastUpdated": wv['LastUpdated'],
"WatchValues": {"SeriesYear": wv_seriesyear,
"LatestDate": latestdate,
"ComicVersion": wv_comicversion,
"Type": wv_type,
"Publisher": wv_publisher,
"Total": wv_total,
"ComicID": wv_comicid,
"IsArc": False}
})
ccnt=0
nm=0
for cs in watchvals:
wm = filechecker.FileChecker(watchcomic=cs['ComicName'], Publisher=cs['ComicPublisher'], AlternateSearch=cs['AlternateSearch'], manual=cs['WatchValues'])
watchmatch = wm.matchIT(fl)
if watchmatch['process_status'] == 'fail':
nm+=1
continue
else:
try:
if cs['WatchValues']['Type'] == 'TPB' and cs['WatchValues']['Total'] > 1:
if watchmatch['series_volume'] is not None:
just_the_digits = re.sub('[^0-9]', '', watchmatch['series_volume']).strip()
else:
just_the_digits = re.sub('[^0-9]', '', watchmatch['justthedigits']).strip()
else:
just_the_digits = watchmatch['justthedigits']
except Exception as e:
logger.warn('[Exception: %s] Unable to properly match up/retrieve issue number (or volume) for this [CS: %s] [WATCHMATCH: %s]' % (e, cs, watchmatch))
nm+=1
continue
if just_the_digits is not None:
temploc= just_the_digits.replace('_', ' ')
temploc = re.sub('[\#\']', '', temploc)
#logger.fdebug('temploc: %s' % temploc)
else:
temploc = None
datematch = "False"
if temploc is None and all([cs['WatchValues']['Type'] != 'TPB', cs['WatchValues']['Type'] != 'One-Shot']):
logger.info('this should have an issue number to match to this particular series: %s' % cs['ComicID'])
continue
if temploc is not None and (any(['annual' in temploc.lower(), 'special' in temploc.lower()]) and mylar.CONFIG.ANNUALS_ON is True):
biannchk = re.sub('-', '', temploc.lower()).strip()
if 'biannual' in biannchk:
logger.fdebug('%s Bi-Annual detected.' % module)
fcdigit = helpers.issuedigits(re.sub('biannual', '', str(biannchk)).strip())
else:
if 'annual' in temploc.lower():
fcdigit = helpers.issuedigits(re.sub('annual', '', str(temploc.lower())).strip())
else:
fcdigit = helpers.issuedigits(re.sub('special', '', str(temploc.lower())).strip())
logger.fdebug('%s Annual/Special detected [%s]. ComicID assigned as %s' % (module, fcdigit, cs['ComicID']))
annchk = "yes"
issuechk = myDB.select("SELECT * from annuals WHERE ComicID=? AND Int_IssueNumber=?", [cs['ComicID'], fcdigit])
else:
annchk = "no"
if temploc is not None:
fcdigit = helpers.issuedigits(temploc)
issuechk = myDB.select("SELECT * from issues WHERE ComicID=? AND Int_IssueNumber=?", [cs['ComicID'], fcdigit])
else:
fcdigit = None
issuechk = myDB.select("SELECT * from issues WHERE ComicID=?", [cs['ComicID']])
if not issuechk:
try:
logger.fdebug('%s No corresponding issue #%s found for %s' % (module, temploc, cs['ComicID']))
except:
continue
#check the last refresh date of the series, and if > than an hr try again:
c_date = cs['LastUpdated']
if c_date is None:
logger.error('%s %s failed during a previous add /refresh as it has no Last Update timestamp. Forcing refresh now.' % (module, cs['ComicName']))
else:
c_obj_date = datetime.datetime.strptime(c_date, "%Y-%m-%d %H:%M:%S")
n_date = datetime.datetime.now()
absdiff = abs(n_date - c_obj_date)
hours = (absdiff.days * 24 * 60 * 60 + absdiff.seconds) / 3600.0
if hours < 1:
logger.fdebug('%s %s [%s] Was refreshed less than 1 hours ago. Skipping Refresh at this time so we don\'t hammer things unnecessarily.' % (module, cs['ComicName'], cs['ComicID']))
continue
updater.dbUpdate([cs['ComicID']])
logger.fdebug('%s Succssfully refreshed series - now re-querying against new data for issue #%s.' % (module, temploc))
if annchk == 'yes':
issuechk = myDB.select("SELECT * from annuals WHERE ComicID=? AND Int_IssueNumber=?", [cs['ComicID'], fcdigit])
else:
issuechk = myDB.select("SELECT * from issues WHERE ComicID=? AND Int_IssueNumber=?", [cs['ComicID'], fcdigit])
if not issuechk:
logger.fdebug('%s No corresponding issue #%s found for %s even after refreshing. It might not have the information available as of yet...' % (module, temploc, cs['ComicID']))
continue
for isc in issuechk:
datematch = "True"
datechkit = False
if isc['ReleaseDate'] is not None and isc['ReleaseDate'] != '0000-00-00':
try:
if isc['DigitalDate'] != '0000-00-00' and int(re.sub('-', '', isc['DigitalDate']).strip()) <= int(re.sub('-', '', isc['ReleaseDate']).strip()):
monthval = isc['DigitalDate']
watch_issueyear = isc['DigitalDate'][:4]
else:
monthval = isc['ReleaseDate']
watch_issueyear = isc['ReleaseDate'][:4]
except:
monthval = isc['ReleaseDate']
watch_issueyear = isc['ReleaseDate'][:4]
else:
try:
if isc['DigitalDate'] != '0000-00-00' and int(re.sub('-', '', isc['DigitalDate']).strip()) <= int(re.sub('-', '', isc['ReleaseDate']).strip()):
monthval = isc['DigitalDate']
watch_issueyear = isc['DigitalDate'][:4]
else:
monthval = isc['IssueDate']
watch_issueyear = isc['IssueDate'][:4]
except:
monthval = isc['IssueDate']
watch_issueyear = isc['IssueDate'][:4]
if len(watchmatch) >= 1 and watchmatch['issue_year'] is not None:
#if the # of matches is more than 1, we need to make sure we get the right series
#compare the ReleaseDate for the issue, to the found issue date in the filename.
#if ReleaseDate doesn't exist, use IssueDate
#if no issue date was found, then ignore.
logger.fdebug('%s[ISSUE-VERIFY] Now checking against %s - %s' % (module, cs['ComicName'], cs['ComicID']))
issyr = None
#logger.fdebug(module + ' issuedate:' + str(isc['IssueDate']))
#logger.fdebug(module + ' isc: ' + str(isc['IssueDate'][5:7]))
#logger.info(module + ' ReleaseDate: ' + str(isc['ReleaseDate']))
#logger.info(module + ' IssueDate: ' + str(isc['IssueDate']))
if isc['DigitalDate'] is not None and isc['DigitalDate'] != '0000-00-00':
if int(isc['DigitalDate'][:4]) < int(watchmatch['issue_year']):
logger.fdebug('%s[ISSUE-VERIFY] %s is before the issue year of %s that was discovered in the filename' % (module, isc['DigitalDate'], watchmatch['issue_year']))
datematch = "False"
elif isc['ReleaseDate'] is not None and isc['ReleaseDate'] != '0000-00-00':
if int(isc['ReleaseDate'][:4]) < int(watchmatch['issue_year']):
logger.fdebug('%s[ISSUE-VERIFY] %s is before the issue year of %s that was discovered in the filename' % (module, isc['ReleaseDate'], watchmatch['issue_year']))
datematch = "False"
else:
if int(isc['IssueDate'][:4]) < int(watchmatch['issue_year']):
logger.fdebug('%s[ISSUE-VERIFY] %s is before the issue year %s that was discovered in the filename' % (module, isc['IssueDate'], watchmatch['issue_year']))
datematch = "False"
if int(watch_issueyear) != int(watchmatch['issue_year']):
if int(monthval[5:7]) == 11 or int(monthval[5:7]) == 12:
issyr = int(monthval[:4]) + 1
logger.fdebug('%s[ISSUE-VERIFY] IssueYear (issyr) is %s' % (module, issyr))
datechkit = True
elif int(monthval[5:7]) == 1 or int(monthval[5:7]) == 2 or int(monthval[5:7]) == 3:
issyr = int(monthval[:4]) - 1
datechkit = True
if datechkit is True and issyr is not None:
logger.fdebug('%s[ISSUE-VERIFY] %s comparing to %s : rechecking by month-check versus year.' % (module, issyr, watchmatch['issue_year']))
datematch = "True"
if int(issyr) != int(watchmatch['issue_year']):
logger.fdebug('%s[ISSUE-VERIFY][.:FAIL:.] Issue is before the modified issue year of %s' % (module, issyr))
datematch = "False"
else:
if fcdigit is None:
logger.info('%s[ISSUE-VERIFY] Found matching issue for ComicID: %s / IssueID: %s' % (module, cs['ComicID'], isc['IssueID']))
else:
logger.info('%s[ISSUE-VERIFY] Found matching issue # %s for ComicID: %s / IssueID: %s' % (module, fcdigit, cs['ComicID'], isc['IssueID']))
if datematch == "True":
#need to reset this to False here so that the True doesn't carry down and avoid the year checks due to the True
datematch = "False"
lonevol = False
# if we get to here, we need to do some more comparisons just to make sure we have the right volume
# first we chk volume label if it exists, then we drop down to issue year
# if the above both don't exist, and there's more than one series on the watchlist (or the series is > v1)
# then spit out the error message and don't post-process it.
watch_values = cs['WatchValues']
#logger.fdebug('WATCH_VALUES:' + str(watch_values))
if any([watch_values['ComicVersion'] is None, watch_values['ComicVersion'] == 'None']):
tmp_watchlist_vol = '1'
else:
tmp_watchlist_vol = re.sub("[^0-9]", "", watch_values['ComicVersion']).strip()
if all([watchmatch['series_volume'] != 'None', watchmatch['series_volume'] is not None]):
tmp_watchmatch_vol = re.sub("[^0-9]","", watchmatch['series_volume']).strip()
if len(tmp_watchmatch_vol) == 4:
if int(tmp_watchmatch_vol) == int(watch_values['SeriesYear']):
logger.fdebug('%s[ISSUE-VERIFY][SeriesYear-Volume MATCH] Series Year of %s matched to volume/year label of %s' % (module, watch_values['SeriesYear'], tmp_watchmatch_vol))
else:
logger.fdebug('%s[ISSUE-VERIFY][SeriesYear-Volume FAILURE] Series Year of %s DID NOT match to volume/year label of %s' % (module, watch_values['SeriesYear'], tmp_watchmatch_vol))
datematch = "False"
elif len(watchvals) > 1 and int(tmp_watchmatch_vol) >= 1:
if int(tmp_watchmatch_vol) == int(tmp_watchlist_vol):
logger.fdebug('%s[ISSUE-VERIFY][SeriesYear-Volume MATCH] Volume label of series Year of %s matched to volume label of %s' % (module, watch_values['ComicVersion'], watchmatch['series_volume']))
lonevol = True
else:
logger.fdebug('%s[ISSUE-VERIFY][SeriesYear-Volume FAILURE] Volume label of Series Year of %s DID NOT match to volume label of %s' % (module, watch_values['ComicVersion'], watchmatch['series_volume']))
datematch = "False"
else:
if any([tmp_watchlist_vol is None, tmp_watchlist_vol == 'None', tmp_watchlist_vol == '']):
logger.fdebug('%s[ISSUE-VERIFY][NO VOLUME PRESENT] No Volume label present for series. Dropping down to Issue Year matching.' % module)
datematch = "False"
elif len(watchvals) == 1 and int(tmp_watchlist_vol) == 1:
logger.fdebug('%s[ISSUE-VERIFY][Lone Volume MATCH] Volume label of %s indicates only volume for this series on your watchlist.' % (module, watch_values['ComicVersion']))
lonevol = True
elif int(tmp_watchlist_vol) > 1:
logger.fdebug('%s[ISSUE-VERIFY][Lone Volume FAILURE] Volume label of %s indicates that there is more than one volume for this series, but the one on your watchlist has no volume label set.' % (module, watch_values['ComicVersion']))
datematch = "False"
if datematch == "False" and all([watchmatch['issue_year'] is not None, watchmatch['issue_year'] != 'None', watch_issueyear is not None]):
#now we see if the issue year matches exactly to what we have within Mylar.
if int(watch_issueyear) == int(watchmatch['issue_year']):
logger.fdebug('%s[ISSUE-VERIFY][Issue Year MATCH] Issue Year of %s is a match to the year found in the filename of : %s' % (module, watch_issueyear, watchmatch['issue_year']))
datematch = 'True'
else:
logger.fdebug('%s[ISSUE-VERIFY][Issue Year FAILURE] Issue Year of %s does NOT match the year found in the filename of : %s' % (module, watch_issueyear, watchmatch['issue_year']))
logger.fdebug('%s[ISSUE-VERIFY] Checking against complete date to see if month published could allow for different publication year.' % module)
if issyr is not None:
if int(issyr) != int(watchmatch['issue_year']):
logger.fdebug('%s[ISSUE-VERIFY][Issue Year FAILURE] Modified Issue year of %s is before the modified issue year of %s' % (module, issyr, watchmatch['issue_year']))
else:
logger.fdebug('%s[ISSUE-VERIFY][Issue Year MATCH] Modified Issue Year of %s is a match to the year found in the filename of : %s' % (module, issyr, watchmatch['issue_year']))
datematch = 'True'
elif datematch == 'False' and watchmatch['issue_year'] is None and lonevol is True:
logger.fdebug('%s[LONE-VOLUME/NO YEAR][MATCH] Only Volume on watchlist matches, no year present in filename. Assuming match based on volume and title.' % module)
datematch = 'True'
if datematch == 'True':
if watchmatch['sub']:
logger.fdebug('%s[SUB: %s][CLOCATION: %s]' % (module, watchmatch['sub'], watchmatch['comiclocation']))
clocation = os.path.join(watchmatch['comiclocation'], watchmatch['sub'], helpers.conversion(watchmatch['comicfilename']))
if not os.path.exists(clocation):
scrubs = re.sub(watchmatch['comiclocation'], '', watchmatch['sub']).strip()
if scrubs[:2] == '//' or scrubs[:2] == '\\':
scrubs = scrubs[1:]
if os.path.exists(scrubs):
logger.fdebug('[MODIFIED CLOCATION] %s' % scrubs)
clocation = scrubs
else:
logger.fdebug('%s[CLOCATION] %s' % (module, watchmatch['comiclocation']))
if self.issueid is not None and os.path.isfile(watchmatch['comiclocation']):
clocation = watchmatch['comiclocation']
else:
clocation = os.path.join(watchmatch['comiclocation'],helpers.conversion(watchmatch['comicfilename']))
annualtype = None
if annchk == 'yes':
if 'Annual' in isc['ReleaseComicName']:
annualtype = 'Annual'
elif 'Special' in isc['ReleaseComicName']:
annualtype = 'Special'
else:
if 'Annual' in isc['ComicName']:
annualtype = 'Annual'
elif 'Special' in isc['ComicName']:
annualtype = 'Special'
manual_list.append({"ComicLocation": clocation,
"ComicID": cs['ComicID'],
"IssueID": isc['IssueID'],
"IssueNumber": isc['Issue_Number'],
"AnnualType": annualtype,
"ComicName": cs['ComicName'],
"Series": watchmatch['series_name'],
"AltSeries": watchmatch['alt_series'],
"One-Off": False,
"ForcedMatch": False})
break
else:
logger.fdebug('%s[NON-MATCH: %s-%s] Incorrect series - not populating..continuing post-processing' % (module, cs['ComicName'], cs['ComicID']))
continue
else:
logger.fdebug('%s[NON-MATCH: %s-%s] Incorrect series - not populating..continuing post-processing' % (module, cs['ComicName'], cs['ComicID']))
continue
if datematch == 'True':
xmld = filechecker.FileChecker()
xmld1 = xmld.dynamic_replace(helpers.conversion(cs['ComicName']))
xseries = xmld1['mod_seriesname'].lower()
xmld2 = xmld.dynamic_replace(helpers.conversion(watchmatch['series_name']))
xfile = xmld2['mod_seriesname'].lower()
if re.sub('\|', '', xseries) == re.sub('\|', '', xfile):
logger.fdebug('%s[DEFINITIVE-NAME MATCH] Definitive name match exactly to : %s [%s]' % (module, watchmatch['series_name'], cs['ComicID']))
if len(manual_list) > 1:
manual_list = [item for item in manual_list if all([item['IssueID'] == isc['IssueID'], item['AnnualType'] is not None]) or all([item['IssueID'] == isc['IssueID'], item['ComicLocation'] == clocation]) or all([item['IssueID'] != isc['IssueID'], item['ComicLocation'] != clocation])]
self.matched = True
else:
continue #break
if datematch == 'True':
logger.fdebug('%s[SUCCESSFUL MATCH: %s-%s] Match verified for %s' % (module, cs['ComicName'], cs['ComicID'], helpers.conversion(fl['comicfilename'])))
break
elif self.matched is True:
logger.warn('%s[MATCH: %s - %s] We matched by name for this series, but cannot find a corresponding issue number in the series list.' % (module, cs['ComicName'], cs['ComicID']))
#we should setup for manual post-processing of story-arc issues here
#we can also search by ComicID to just grab those particular arcs as an alternative as well (not done)
#as_d = filechecker.FileChecker()
#as_dinfo = as_d.dynamic_replace(helpers.conversion(fl['series_name']))
#mod_seriesname = as_dinfo['mod_seriesname']
#arcloopchk = []
#for x in alt_list:
# cname = x['AS_DyComicName']
# for ab in x['AS_Alt']:
# if re.sub('[\|\s]', '', mod_seriesname.lower()).strip() in re.sub('[\|\s]', '', ab.lower()).strip():
# if not any(re.sub('[\|\s]', '', cname.lower()) == x for x in arcloopchk):
# arcloopchk.append(re.sub('[\|\s]', '', cname.lower()))
##make sure we add back in the original parsed filename here.
#if not any(re.sub('[\|\s]', '', mod_seriesname).lower() == x for x in arcloopchk):
# arcloopchk.append(re.sub('[\|\s]', '', mod_seriesname.lower()))
if self.issuearcid is None:
tmpsql = "SELECT * FROM storyarcs WHERE DynamicComicName IN ({seq}) COLLATE NOCASE".format(seq=','.join('?' * len(loopchk))) #len(arcloopchk)))
arc_series = myDB.select(tmpsql, tuple(loopchk)) #arcloopchk))
else:
if self.issuearcid[0] == 'S':
self.issuearcid = self.issuearcid[1:]
arc_series = myDB.select("SELECT * FROM storyarcs WHERE IssueArcID=?", [self.issuearcid])
if arc_series is None:
logger.error('%s No Story Arcs in Watchlist that contain that particular series - aborting Manual Post Processing. Maybe you should be running Import?' % module)
return
else:
arcvals = []
for av in arc_series:
arcvals.append({"ComicName": av['ComicName'],
"ArcValues": {"StoryArc": av['StoryArc'],
"StoryArcID": av['StoryArcID'],
"IssueArcID": av['IssueArcID'],
"ComicName": av['ComicName'],
"DynamicComicName": av['DynamicComicName'],
"ComicPublisher": av['IssuePublisher'],
"Publisher": av['Publisher'],
"IssueID": av['IssueID'],
"IssueNumber": av['IssueNumber'],
"IssueYear": av['IssueYear'], #for some reason this is empty
"ReadingOrder": av['ReadingOrder'],
"IssueDate": av['IssueDate'],
"Status": av['Status'],
"Location": av['Location']},
"WatchValues": {"SeriesYear": av['SeriesYear'],
"LatestDate": av['IssueDate'],
"ComicVersion": av['Volume'],
"ComicID": av['ComicID'],
"Publisher": av['IssuePublisher'],
"Total": av['TotalIssues'], # this will return the total issues in the arc (not needed for this)
"Type": av['Type'],
"IsArc": True}
})
ccnt=0
nm=0
from collections import defaultdict
res = defaultdict(list)
for acv in arcvals:
if len(manual_list) == 0:
res[acv['ComicName']].append({"ArcValues": acv['ArcValues'],
"WatchValues": acv['WatchValues']})
else:
acv_check = [x for x in manual_list if x['ComicID'] == acv['WatchValues']['ComicID']]
if acv_check:
res[acv['ComicName']].append({"ArcValues": acv['ArcValues'],
"WatchValues": acv['WatchValues']})
if len(res) > 0:
logger.fdebug('%s Now Checking if %s issue(s) may also reside in one of the storyarc\'s that I am watching.' % (module, len(res)))
for k,v in res.items():
i = 0
#k is ComicName
#v is ArcValues and WatchValues
while i < len(v):
if k is None or k == 'None':
pass
else:
arcm = filechecker.FileChecker(watchcomic=k, Publisher=v[i]['ArcValues']['ComicPublisher'], manual=v[i]['WatchValues'])
arcmatch = arcm.matchIT(fl)
#logger.fdebug('arcmatch: ' + str(arcmatch))
if arcmatch['process_status'] == 'fail':
nm+=1
else:
try:
if all([v[i]['WatchValues']['Type'] == 'TPB', v[i]['WatchValues']['Total'] > 1]) or all([v[i]['WatchValues']['Type'] == 'One-Shot', v[i]['WatchValues']['Total'] == 1]):
if watchmatch['series_volume'] is not None:
just_the_digits = re.sub('[^0-9]', '', arcmatch['series_volume']).strip()
else:
just_the_digits = re.sub('[^0-9]', '', arcmatch['justthedigits']).strip()
else:
just_the_digits = arcmatch['justthedigits']
except Exception as e:
logger.warn('[Exception: %s] Unable to properly match up/retrieve issue number (or volume) for this [CS: %s] [WATCHMATCH: %s]' % (e, v[i]['ArcValues'], v[i]['WatchValues']))
nm+=1
continue
if just_the_digits is not None:
temploc= just_the_digits.replace('_', ' ')
temploc = re.sub('[\#\']', '', temploc)
#logger.fdebug('temploc: %s' % temploc)
else:
if any([v[i]['WatchValues']['Type'] == 'TPB', v[i]['WatchValues']['Type'] == 'One-Shot']):
temploc = '1'
else:
temploc = None
if temploc is not None and helpers.issuedigits(temploc) != helpers.issuedigits(v[i]['ArcValues']['IssueNumber']):
#logger.fdebug('issues dont match. Skipping')
i+=1
continue
else:
if temploc is not None and (any(['annual' in temploc.lower(), 'special' in temploc.lower()]) and mylar.CONFIG.ANNUALS_ON is True):
biannchk = re.sub('-', '', temploc.lower()).strip()
if 'biannual' in biannchk:
logger.fdebug('%s Bi-Annual detected.' % module)
fcdigit = helpers.issuedigits(re.sub('biannual', '', str(biannchk)).strip())
else:
if 'annual' in temploc.lower():
fcdigit = helpers.issuedigits(re.sub('annual', '', str(temploc.lower())).strip())
else:
fcdigit = helpers.issuedigits(re.sub('special', '', str(temploc.lower())).strip())
logger.fdebug('%s Annual detected [%s]. ComicID assigned as %s' % (module, fcdigit, v[i]['WatchValues']['ComicID']))
annchk = "yes"
issuechk = myDB.selectone("SELECT * from storyarcs WHERE ComicID=? AND Int_IssueNumber=?", [v[i]['WatchValues']['ComicID'], fcdigit]).fetchone()
else:
annchk = "no"
if temploc is not None:
fcdigit = helpers.issuedigits(temploc)
issuechk = myDB.select("SELECT * from storyarcs WHERE ComicID=? AND Int_IssueNumber=?", [v[i]['WatchValues']['ComicID'], fcdigit])
else:
fcdigit = None
issuechk = myDB.select("SELECT * from storyarcs WHERE ComicID=?", [v[i]['WatchValues']['ComicID']])
if issuechk is None:
try:
logger.fdebug('%s No corresponding issue # found for %s' % (module, v[i]['WatchValues']['ComicID']))
except:
continue
else:
for isc in issuechk:
datematch = "True"
datechkit = False
if isc['ReleaseDate'] is not None and isc['ReleaseDate'] != '0000-00-00':
try:
if isc['DigitalDate'] != '0000-00-00' and int(re.sub('-', '', isc['DigitalDate']).strip()) <= int(re.sub('-', '', isc['ReleaseDate']).strip()):
monthval = isc['DigitalDate']
arc_issueyear = isc['DigitalDate'][:4]
else:
monthval = isc['ReleaseDate']
arc_issueyear = isc['ReleaseDate'][:4]
except:
monthval = isc['ReleaseDate']
arc_issueyear = isc['ReleaseDate'][:4]
else:
try:
if isc['DigitalDate'] != '0000-00-00' and int(re.sub('-', '', isc['DigitalDate']).strip()) <= int(re.sub('-', '', isc['ReleaseDate']).strip()):
monthval = isc['DigitalDate']
arc_issueyear = isc['DigitalDate'][:4]
else:
monthval = isc['IssueDate']
arc_issueyear = isc['IssueDate'][:4]
except:
monthval = isc['IssueDate']
arc_issueyear = isc['IssueDate'][:4]
if len(arcmatch) >= 1 and arcmatch['issue_year'] is not None:
#if the # of matches is more than 1, we need to make sure we get the right series
#compare the ReleaseDate for the issue, to the found issue date in the filename.
#if ReleaseDate doesn't exist, use IssueDate
#if no issue date was found, then ignore.
logger.fdebug('%s[ARC ISSUE-VERIFY] Now checking against %s - %s' % (module, k, v[i]['WatchValues']['ComicID']))
issyr = None
#logger.fdebug('issuedate: %s' % isc['IssueDate'])
#logger.fdebug('issuechk: %s' % isc['IssueDate'][5:7])
#logger.fdebug('StoreDate %s' % isc['ReleaseDate'])
#logger.fdebug('IssueDate: %s' % isc['IssueDate'])
if isc['DigitalDate'] is not None and isc['DigitalDate'] != '0000-00-00':
if int(isc['DigitalDate'][:4]) < int(arcmatch['issue_year']):
logger.fdebug('%s[ARC ISSUE-VERIFY] %s is before the issue year of %s that was discovered in the filename' % (module, isc['DigitalDate'], arcmatch['issue_year']))
datematch = "False"
elif all([isc['ReleaseDate'] is not None, isc['ReleaseDate'] != '0000-00-00']):
if isc['ReleaseDate'] == '0000-00-00':
datevalue = isc['IssueDate']
else:
datevalue = isc['ReleaseDate']
if int(datevalue[:4]) < int(arcmatch['issue_year']):
logger.fdebug('%s[ARC ISSUE-VERIFY] %s is before the issue year %s that was discovered in the filename' % (module, datevalue[:4], arcmatch['issue_year']))
datematch = "False"
elif all([isc['IssueDate'] is not None, isc['IssueDate'] != '0000-00-00']):
if isc['IssueDate'] == '0000-00-00':
datevalue = isc['ReleaseDate']
else:
datevalue = isc['IssueDate']
if int(datevalue[:4]) < int(arcmatch['issue_year']):
logger.fdebug('%s[ARC ISSUE-VERIFY] %s is before the issue year of %s that was discovered in the filename' % (module, datevalue[:4], arcmatch['issue_year']))
datematch = "False"
else:
if int(isc['IssueDate'][:4]) < int(arcmatch['issue_year']):
logger.fdebug('%s[ARC ISSUE-VERIFY] %s is before the issue year %s that was discovered in the filename' % (module, isc['IssueDate'], arcmatch['issue_year']))
datematch = "False"
if int(arc_issueyear) != int(arcmatch['issue_year']):
if int(monthval[5:7]) == 11 or int(monthval[5:7]) == 12:
issyr = int(monthval[:4]) + 1
datechkit = True
logger.fdebug('%s[ARC ISSUE-VERIFY] IssueYear (issyr) is %s' % (module, issyr))
elif int(monthval[5:7]) == 1 or int(monthval[5:7]) == 2 or int(monthval[5:7]) == 3:
issyr = int(monthval[:4]) - 1
datechkit = True
if datechkit is True and issyr is not None:
logger.fdebug('%s[ARC ISSUE-VERIFY] %s comparing to %s : rechecking by month-check versus year.' % (module, issyr, arcmatch['issue_year']))
datematch = "True"
if int(issyr) != int(arcmatch['issue_year']):
logger.fdebug('%s[.:FAIL:.] Issue is before the modified issue year of %s' % (module, issyr))
datematch = "False"
else:
if fcdigit is None:
logger.info('%s Found matching issue for ComicID: %s / IssueID: %s' % (module, v[i]['WatchValues']['ComicID'], isc['IssueID']))
else:
logger.info('%s Found matching issue # %s for ComicID: %s / IssueID: %s' % (module, fcdigit, v[i]['WatchValues']['ComicID'], isc['IssueID']))
logger.fdebug('datematch: %s' % datematch)
logger.fdebug('temploc: %s' % helpers.issuedigits(temploc))
logger.fdebug('arcissue: %s' % helpers.issuedigits(v[i]['ArcValues']['IssueNumber']))
if datematch == "True" and helpers.issuedigits(temploc) == helpers.issuedigits(v[i]['ArcValues']['IssueNumber']):
#reset datematch here so it doesn't carry the value down and avoid year checks
datematch = "False"
arc_values = v[i]['WatchValues']
if any([arc_values['ComicVersion'] is None, arc_values['ComicVersion'] == 'None']):
tmp_arclist_vol = '1'
else:
tmp_arclist_vol = re.sub("[^0-9]", "", arc_values['ComicVersion']).strip()
if all([arcmatch['series_volume'] != 'None', arcmatch['series_volume'] is not None]):
tmp_arcmatch_vol = re.sub("[^0-9]","", arcmatch['series_volume']).strip()
if len(tmp_arcmatch_vol) == 4:
if int(tmp_arcmatch_vol) == int(arc_values['SeriesYear']):
logger.fdebug('%s[ARC ISSUE-VERIFY][SeriesYear-Volume MATCH] Series Year of %s matched to volume/year label of %s' % (module, arc_values['SeriesYear'], tmp_arcmatch_vol))
else:
logger.fdebug('%s[ARC ISSUE-VERIFY][SeriesYear-Volume FAILURE] Series Year of %s DID NOT match to volume/year label of %s' % (module, arc_values['SeriesYear'], tmp_arcmatch_vol))
datematch = "False"
if len(arcvals) > 1 and int(tmp_arcmatch_vol) >= 1:
if int(tmp_arcmatch_vol) == int(tmp_arclist_vol):
logger.fdebug('%s[ARC ISSUE-VERIFY][SeriesYear-Volume MATCH] Volume label of series Year of %s matched to volume label of %s' % (module, arc_values['ComicVersion'], arcmatch['series_volume']))
else:
logger.fdebug('%s[ARC ISSUE-VERIFY][SeriesYear-Volume FAILURE] Volume label of Series Year of %s DID NOT match to volume label of %s' % (module, arc_values['ComicVersion'], arcmatch['series_volume']))
datematch = "False"
else:
if any([tmp_arclist_vol is None, tmp_arclist_vol == 'None', tmp_arclist_vol == '']):
logger.fdebug('%s[ARC ISSUE-VERIFY][NO VOLUME PRESENT] No Volume label present for series. Dropping down to Issue Year matching.' % module)
datematch = "False"
elif len(arcvals) == 1 and int(tmp_arclist_vol) == 1:
logger.fdebug('%s[ARC ISSUE-VERIFY][Lone Volume MATCH] Volume label of %s indicates only volume for this series on your watchlist.' % (module, arc_values['ComicVersion']))
elif int(tmp_arclist_vol) > 1:
logger.fdebug('%s[ARC ISSUE-VERIFY][Lone Volume FAILURE] Volume label of %s indicates that there is more than one volume for this series, but the one on your watchlist has no volume label set.' % (module, arc_values['ComicVersion']))
datematch = "False"
if datematch == "False" and all([arcmatch['issue_year'] is not None, arcmatch['issue_year'] != 'None', arc_issueyear is not None]):
#now we see if the issue year matches exactly to what we have within Mylar.
if int(arc_issueyear) == int(arcmatch['issue_year']):
logger.fdebug('%s[ARC ISSUE-VERIFY][Issue Year MATCH] Issue Year of %s is a match to the year found in the filename of : %s' % (module, arc_issueyear, arcmatch['issue_year']))
datematch = 'True'
else:
logger.fdebug('%s[ARC ISSUE-VERIFY][Issue Year FAILURE] Issue Year of %s does NOT match the year found in the filename of : %s' % (module, arc_issueyear, arcmatch['issue_year']))
logger.fdebug('%s[ARC ISSUE-VERIFY] Checking against complete date to see if month published could allow for different publication year.' % module)
if issyr is not None:
if int(issyr) != int(arcmatch['issue_year']):
logger.fdebug('%s[ARC ISSUE-VERIFY][Issue Year FAILURE] Modified Issue year of %s is before the modified issue year of %s' % (module, issyr, arcmatch['issue_year']))
else:
logger.fdebug('%s[ARC ISSUE-VERIFY][Issue Year MATCH] Modified Issue Year of %s is a match to the year found in the filename of : %s' % (module, issyr, arcmatch['issue_year']))
datematch = 'True'
if datematch == 'True':
passit = False
if len(manual_list) > 0:
if any([ v[i]['ArcValues']['IssueID'] == x['IssueID'] for x in manual_list ]):
logger.info('[STORY-ARC POST-PROCESSING] IssueID %s exists in your watchlist. Bypassing Story-Arc post-processing performed later.' % v[i]['ArcValues']['IssueID'])
#add in the storyarcid into the manual list so it will perform story-arc functions after normal manual PP is finished.
for a in manual_list:
if a['IssueID'] == v[i]['ArcValues']['IssueID']:
a['IssueArcID'] = v[i]['ArcValues']['IssueArcID']
break
passit = True
if passit == False:
tmpfilename = helpers.conversion(arcmatch['comicfilename'])
if arcmatch['sub']:
clocation = os.path.join(arcmatch['comiclocation'], arcmatch['sub'], tmpfilename)
else:
clocation = os.path.join(arcmatch['comiclocation'], tmpfilename)
logger.info('[%s #%s] MATCH: %s / %s / %s' % (k, isc['IssueNumber'], clocation, isc['IssueID'], v[i]['ArcValues']['IssueID']))
if v[i]['ArcValues']['Publisher'] is None:
arcpublisher = v[i]['ArcValues']['ComicPublisher']
else:
arcpublisher = v[i]['ArcValues']['Publisher']
manual_arclist.append({"ComicLocation": clocation,
"Filename": tmpfilename,
"ComicID": v[i]['WatchValues']['ComicID'],
"IssueID": v[i]['ArcValues']['IssueID'],
"IssueNumber": v[i]['ArcValues']['IssueNumber'],
"StoryArc": v[i]['ArcValues']['StoryArc'],
"StoryArcID": v[i]['ArcValues']['StoryArcID'],
"IssueArcID": v[i]['ArcValues']['IssueArcID'],
"Publisher": arcpublisher,
"ReadingOrder": v[i]['ArcValues']['ReadingOrder'],
"ComicName": k})
logger.info('%s[SUCCESSFUL MATCH: %s-%s] Match verified for %s' % (module, k, v[i]['WatchValues']['ComicID'], arcmatch['comicfilename']))
self.matched = True
break
else:
logger.fdebug('%s[NON-MATCH: %s-%s] Incorrect series - not populating..continuing post-processing' % (module, k, v[i]['WatchValues']['ComicID']))
i+=1
if self.matched is False:
#one-off manual pp'd of torrents
if all(['0-Day Week' in self.nzb_name, mylar.CONFIG.PACK_0DAY_WATCHLIST_ONLY is True]):
pass
else:
oneofflist = myDB.select("select s.Issue_Number, s.ComicName, s.IssueID, s.ComicID, s.Provider, w.format, w.PUBLISHER, w.weeknumber, w.year from snatched as s inner join nzblog as n on s.IssueID = n.IssueID inner join weekly as w on s.IssueID = w.IssueID WHERE n.OneOff = 1;") #(s.Provider ='32P' or s.Provider='WWT' or s.Provider='DEM') AND n.OneOff = 1;")
#oneofflist = myDB.select("select s.Issue_Number, s.ComicName, s.IssueID, s.ComicID, s.Provider, w.PUBLISHER, w.weeknumber, w.year from snatched as s inner join nzblog as n on s.IssueID = n.IssueID and s.Hash is not NULL inner join weekly as w on s.IssueID = w.IssueID WHERE n.OneOff = 1;") #(s.Provider ='32P' or s.Provider='WWT' or s.Provider='DEM') AND n.OneOff = 1;")
if not oneofflist:
pass #continue
else:
logger.fdebug('%s[ONEOFF-SELECTION][self.nzb_name: %s]' % (module, self.nzb_name))
oneoffvals = []
for ofl in oneofflist:
#logger.info('[ONEOFF-SELECTION] ofl: %s' % ofl)
oneoffvals.append({"ComicName": ofl['ComicName'],
"ComicPublisher": ofl['PUBLISHER'],
"Issue_Number": ofl['Issue_Number'],
"AlternateSearch": None,
"ComicID": ofl['ComicID'],
"IssueID": ofl['IssueID'],
"WatchValues": {"SeriesYear": None,
"LatestDate": None,
"ComicVersion": None,
"Publisher": ofl['PUBLISHER'],
"Total": None,
"Type": ofl['format'],
"ComicID": ofl['ComicID'],
"IsArc": False}})
#this seems redundant to scan in all over again...
#for fl in filelist['comiclist']:
for ofv in oneoffvals:
#logger.info('[ONEOFF-SELECTION] ofv: %s' % ofv)
wm = filechecker.FileChecker(watchcomic=ofv['ComicName'], Publisher=ofv['ComicPublisher'], AlternateSearch=None, manual=ofv['WatchValues'])
#if fl['sub'] is not None:
# pathtofile = os.path.join(fl['comiclocation'], fl['sub'], fl['comicfilename'])
#else:
# pathtofile = os.path.join(fl['comiclocation'], fl['comicfilename'])
watchmatch = wm.matchIT(fl)
if watchmatch['process_status'] == 'fail':
nm+=1
continue
else:
try:
if ofv['WatchValues']['Type'] is not None and ofv['WatchValues']['Total'] > 1:
if watchmatch['series_volume'] is not None:
just_the_digits = re.sub('[^0-9]', '', watchmatch['series_volume']).strip()
else:
just_the_digits = re.sub('[^0-9]', '', watchmatch['justthedigits']).strip()
else:
just_the_digits = watchmatch['justthedigits']
except Exception as e:
logger.warn('[Exception: %s] Unable to properly match up/retrieve issue number (or volume) for this [CS: %s] [WATCHMATCH: %s]' % (e, cs, watchmatch))
nm+=1
continue
if just_the_digits is not None:
temploc= just_the_digits.replace('_', ' ')
temploc = re.sub('[\#\']', '', temploc)
logger.fdebug('temploc: %s' % temploc)
else:
temploc = None
logger.info('watchmatch: %s' % watchmatch)
if temploc is not None:
if 'annual' in temploc.lower():
biannchk = re.sub('-', '', temploc.lower()).strip()
if 'biannual' in biannchk:
logger.fdebug('%s Bi-Annual detected.' % module)
fcdigit = helpers.issuedigits(re.sub('biannual', '', str(biannchk)).strip())
else:
fcdigit = helpers.issuedigits(re.sub('annual', '', str(temploc.lower())).strip())
logger.fdebug('%s Annual detected [%s]. ComicID assigned as %s' % (module, fcdigit, ofv['ComicID']))
annchk = "yes"
else:
fcdigit = helpers.issuedigits(temploc)
if temploc is not None and fcdigit == helpers.issuedigits(ofv['Issue_Number']) or all([temploc is None, helpers.issuedigits(ofv['Issue_Number']) == '1']):
if watchmatch['sub']:
clocation = os.path.join(watchmatch['comiclocation'], watchmatch['sub'], helpers.conversion(watchmatch['comicfilename']))
if not os.path.exists(clocation):
scrubs = re.sub(watchmatch['comiclocation'], '', watchmatch['sub']).strip()
if scrubs[:2] == '//' or scrubs[:2] == '\\':
scrubs = scrubs[1:]
if os.path.exists(scrubs):
logger.fdebug('[MODIFIED CLOCATION] %s' % scrubs)
clocation = scrubs
else:
if self.issueid is not None and os.path.isfile(watchmatch['comiclocation']):
clocation = watchmatch['comiclocation']
else:
clocation = os.path.join(watchmatch['comiclocation'],helpers.conversion(watchmatch['comicfilename']))
oneoff_issuelist.append({"ComicLocation": clocation,
"ComicID": ofv['ComicID'],
"IssueID": ofv['IssueID'],
"IssueNumber": ofv['Issue_Number'],
"ComicName": ofv['ComicName'],
"One-Off": True})
self.oneoffinlist = True
else:
logger.fdebug('%s No corresponding issue # in dB found for %s # %s' % (module, ofv['ComicName'], ofv['Issue_Number']))
continue
logger.fdebug('%s[SUCCESSFUL MATCH: %s-%s] Match Verified for %s' % (module, ofv['ComicName'], ofv['ComicID'], helpers.conversion(fl['comicfilename'])))
self.matched = True
break
if filelist['comiccount'] > 0:
logger.fdebug('%s There are %s files found that match on your watchlist, %s files are considered one-off\'s, and %s files do not match anything' % (module, len(manual_list), len(oneoff_issuelist), int(filelist['comiccount']) - len(manual_list)))
delete_arc = []
if len(manual_arclist) > 0:
logger.info('[STORY-ARC MANUAL POST-PROCESSING] I have found %s issues that belong to Story Arcs. Flinging them into the correct directories.' % len(manual_arclist))
for ml in manual_arclist:
issueid = ml['IssueID']
ofilename = orig_filename = ml['ComicLocation']
logger.info('[STORY-ARC POST-PROCESSING] Enabled for %s' % ml['StoryArc'])
if all([mylar.CONFIG.STORYARCDIR is True, mylar.CONFIG.COPY2ARCDIR is True]):
grdst = helpers.arcformat(ml['StoryArc'], helpers.spantheyears(ml['StoryArcID']), ml['Publisher'])
logger.info('grdst: %s' % grdst)
#tag the meta.
metaresponse = None
crcvalue = helpers.crc(ofilename)
if mylar.CONFIG.ENABLE_META:
logger.info('[STORY-ARC POST-PROCESSING] Metatagging enabled - proceeding...')
try:
import cmtagmylar
metaresponse = cmtagmylar.run(self.nzb_folder, issueid=issueid, filename=ofilename)
except ImportError:
logger.warn('%s comictaggerlib not found on system. Ensure the ENTIRE lib directory is located within mylar/lib/comictaggerlib/' % module)
metaresponse = "fail"
if metaresponse == "fail":
logger.fdebug('%s Unable to write metadata successfully - check mylar.log file. Attempting to continue without metatagging...' % module)
elif any([metaresponse == "unrar error", metaresponse == "corrupt"]):
logger.error('%s This is a corrupt archive - whether CRC errors or it is incomplete. Marking as BAD, and retrying it.' % module)
continue
#launch failed download handling here.
elif metaresponse.startswith('file not found'):
filename_in_error = metaresponse.split('||')[1]
self._log("The file cannot be found in the location provided for metatagging to be used [%s]. Please verify it exists, and re-run if necessary. Attempting to continue without metatagging..." % (filename_in_error))
logger.error('%s The file cannot be found in the location provided for metatagging to be used [%s]. Please verify it exists, and re-run if necessary. Attempting to continue without metatagging...' % (module, filename_in_error))
else:
odir = os.path.split(metaresponse)[0]
ofilename = os.path.split(metaresponse)[1]
ext = os.path.splitext(metaresponse)[1]
logger.info('%s Sucessfully wrote metadata to .cbz (%s) - Continuing..' % (module, ofilename))
self._log('Sucessfully wrote metadata to .cbz (%s) - proceeding...' % ofilename)
dfilename = ofilename
else:
dfilename = ml['Filename']
if metaresponse:
src_location = odir
grab_src = os.path.join(src_location, ofilename)
else:
src_location = ofilename
grab_src = ofilename
logger.fdebug('%s Source Path : %s' % (module, grab_src))
checkdirectory = filechecker.validateAndCreateDirectory(grdst, True, module=module)
if not checkdirectory:
logger.warn('%s Error trying to validate/create directory. Aborting this process at this time.' % module)
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
#send to renamer here if valid.
if mylar.CONFIG.RENAME_FILES:
renamed_file = helpers.rename_param(ml['ComicID'], ml['ComicName'], ml['IssueNumber'], dfilename, issueid=ml['IssueID'], arc=ml['StoryArc'])
if renamed_file:
dfilename = renamed_file['nfilename']
logger.fdebug('%s Renaming file to conform to configuration: %s' % (module, ofilename))
#if from a StoryArc, check to see if we're appending the ReadingOrder to the filename
if mylar.CONFIG.READ2FILENAME:
logger.fdebug('%s readingorder#: %s' % (module, ml['ReadingOrder']))
if int(ml['ReadingOrder']) < 10: readord = "00" + str(ml['ReadingOrder'])
elif int(ml['ReadingOrder']) >= 10 and int(ml['ReadingOrder']) <= 99: readord = "0" + str(ml['ReadingOrder'])
else: readord = str(ml['ReadingOrder'])
dfilename = str(readord) + "-" + os.path.split(dfilename)[1]
grab_dst = os.path.join(grdst, dfilename)
logger.fdebug('%s Destination Path : %s' % (module, grab_dst))
logger.fdebug('%s Source Path : %s' % (module, grab_src))
logger.info('%s[ONE-OFF MODE][%s] %s into directory : %s' % (module, mylar.CONFIG.ARC_FILEOPS.upper(), grab_src, grab_dst))
#this is also for issues that are part of a story arc, and don't belong to a watchlist series (ie. one-off's)
try:
checkspace = helpers.get_free_space(grdst)
if checkspace is False:
if all([metaresponse is not None, metaresponse != 'fail']): # meta was done
self.tidyup(src_location, True, cacheonly=True)
raise OSError
fileoperation = helpers.file_ops(grab_src, grab_dst, one_off=True)
if not fileoperation:
raise OSError
except Exception as e:
logger.error('%s [ONE-OFF MODE] Failed to %s %s: %s' % (module, mylar.CONFIG.ARC_FILEOPS, grab_src, e))
return
#tidyup old path
if any([mylar.CONFIG.FILE_OPTS == 'move', mylar.CONFIG.FILE_OPTS == 'copy']):
self.tidyup(src_location, True, filename=orig_filename)
#delete entry from nzblog table
#if it was downloaded via mylar from the storyarc section, it will have an 'S' in the nzblog
#if it was downloaded outside of mylar and/or not from the storyarc section, it will be a normal issueid in the nzblog
#IssArcID = 'S' + str(ml['IssueArcID'])
myDB.action('DELETE from nzblog WHERE IssueID=? AND SARC=?', ['S' + str(ml['IssueArcID']),ml['StoryArc']])
myDB.action('DELETE from nzblog WHERE IssueID=? AND SARC=?', [ml['IssueArcID'],ml['StoryArc']])
logger.fdebug('%s IssueArcID: %s' % (module, ml['IssueArcID']))
newVal = {"Status": "Downloaded",
"Location": grab_dst}
else:
newVal = {"Status": "Downloaded",
"Location": ml['ComicLocation']}
ctrlVal = {"IssueArcID": ml['IssueArcID']}
logger.fdebug('writing: %s -- %s' % (newVal, ctrlVal))
myDB.upsert("storyarcs", newVal, ctrlVal)
if all([mylar.CONFIG.STORYARCDIR is True, mylar.CONFIG.COPY2ARCDIR is True]):
logger.fdebug('%s [%s] Post-Processing completed for: %s' % (module, ml['StoryArc'], grab_dst))
else:
logger.fdebug('%s [%s] Post-Processing completed for: %s' % (module, ml['StoryArc'], ml['ComicLocation']))
if (all([self.nzb_name != 'Manual Run', self.apicall is False]) or (self.oneoffinlist is True or all([self.issuearcid is not None, self.issueid is None]))) and not self.nzb_name.startswith('0-Day'): # and all([self.issueid is None, self.comicid is None, self.apicall is False]):
ppinfo = []
if self.oneoffinlist is False:
self.oneoff = False
if any([self.issueid is not None, self.issuearcid is not None]):
if self.issuearcid is not None:
s_id = self.issuearcid
else:
s_id = self.issueid
nzbiss = myDB.selectone('SELECT * FROM nzblog WHERE IssueID=?', [s_id]).fetchone()
if nzbiss is None and self.issuearcid is not None:
nzbiss = myDB.selectone('SELECT * FROM nzblog WHERE IssueID=?', ['S'+s_id]).fetchone()
else:
nzbname = self.nzb_name
#remove extensions from nzb_name if they somehow got through (Experimental most likely)
if nzbname.lower().endswith(self.extensions):
fd, ext = os.path.splitext(nzbname)
self._log("Removed extension from nzb: " + ext)
nzbname = re.sub(str(ext), '', str(nzbname))
#replace spaces
# let's change all space to decimals for simplicity
logger.fdebug('[NZBNAME]: ' + nzbname)
#gotta replace & or escape it
nzbname = re.sub("\&", 'and', nzbname)
nzbname = re.sub('[\,\:\?\'\+]', '', nzbname)
nzbname = re.sub('[\(\)]', ' ', nzbname)
logger.fdebug('[NZBNAME] nzbname (remove chars): ' + nzbname)
nzbname = re.sub('.cbr', '', nzbname).strip()
nzbname = re.sub('.cbz', '', nzbname).strip()
nzbname = re.sub('[\.\_]', ' ', nzbname).strip()
nzbname = re.sub('\s+', ' ', nzbname) #make sure we remove the extra spaces.
logger.fdebug('[NZBNAME] nzbname (remove extensions, double spaces, convert underscores to spaces): ' + nzbname)
nzbname = re.sub('\s', '.', nzbname)
logger.fdebug('%s After conversions, nzbname is : %s' % (module, nzbname))
self._log("nzbname: %s" % nzbname)
nzbiss = myDB.selectone("SELECT * from nzblog WHERE nzbname=? or altnzbname=?", [nzbname, nzbname]).fetchone()
if nzbiss is None:
self._log("Failure - could not initially locate nzbfile in my database to rename.")
logger.fdebug('%s Failure - could not locate nzbfile initially' % module)
# if failed on spaces, change it all to decimals and try again.
nzbname = re.sub('[\(\)]', '', str(nzbname))
self._log("trying again with this nzbname: %s" % nzbname)
logger.fdebug('%s Trying to locate nzbfile again with nzbname of : %s' % (module, nzbname))
nzbiss = myDB.selectone("SELECT * from nzblog WHERE nzbname=? or altnzbname=?", [nzbname, nzbname]).fetchone()
if nzbiss is None:
logger.error('%s Unable to locate downloaded file within items I have snatched. Attempting to parse the filename directly and process.' % module)
#set it up to run manual post-processing on self.nzb_folder
self._log('Unable to locate downloaded file within items I have snatched. Attempting to parse the filename directly and process.')
self.valreturn.append({"self.log": self.log,
"mode": 'outside'})
return self.queue.put(self.valreturn)
else:
self._log("I corrected and found the nzb as : %s" % nzbname)
logger.fdebug('%s Auto-corrected and found the nzb as : %s' % (module, nzbname))
#issueid = nzbiss['IssueID']
issueid = nzbiss['IssueID']
logger.fdebug('%s Issueid: %s' % (module, issueid))
sarc = nzbiss['SARC']
self.oneoff = nzbiss['OneOff']
tmpiss = myDB.selectone('SELECT * FROM issues WHERE IssueID=?', [issueid]).fetchone()
if tmpiss is None:
tmpiss = myDB.selectone('SELECT * FROM annuals WHERE IssueID=?', [issueid]).fetchone()
comicid = None
comicname = None
issuenumber = None
if tmpiss is not None:
ppinfo.append({'comicid': tmpiss['ComicID'],
'issueid': issueid,
'comicname': tmpiss['ComicName'],
'issuenumber': tmpiss['Issue_Number'],
'comiclocation': None,
'publisher': None,
'sarc': sarc,
'oneoff': self.oneoff})
elif all([self.oneoff is not None, issueid[0] == 'S']):
issuearcid = re.sub('S', '', issueid).strip()
oneinfo = myDB.selectone("SELECT * FROM storyarcs WHERE IssueArcID=?", [issuearcid]).fetchone()
if oneinfo is None:
logger.warn('Unable to locate issue as previously snatched arc issue - it might be something else...')
self._log('Unable to locate issue as previously snatched arc issue - it might be something else...')
else:
#reverse lookup the issueid here to see if it possible exists on watchlist...
tmplookup = myDB.selectone('SELECT * FROM comics WHERE ComicID=?', [oneinfo['ComicID']]).fetchone()
if tmplookup is not None:
logger.fdebug('[WATCHLIST-DETECTION-%s] Processing as Arc, detected on watchlist - will PP for both.' % tmplookup['ComicName'])
self.oneoff = False
else:
self.oneoff = True
ppinfo.append({'comicid': oneinfo['ComicID'],
'comicname': oneinfo['ComicName'],
'issuenumber': oneinfo['IssueNumber'],
'publisher': oneinfo['IssuePublisher'],
'comiclocation': None,
'issueid': issueid, #need to keep it so the 'S' is present to denote arc.
'sarc': sarc,
'oneoff': self.oneoff})
if all([len(ppinfo) == 0, self.oneoff is not None, mylar.CONFIG.ALT_PULL == 2]):
oneinfo = myDB.selectone('SELECT * FROM weekly WHERE IssueID=?', [issueid]).fetchone()
if oneinfo is None:
oneinfo = myDB.selectone('SELECT * FROM oneoffhistory WHERE IssueID=?', [issueid]).fetchone()
if oneinfo is None:
logger.warn('Unable to locate issue as previously snatched one-off')
self._log('Unable to locate issue as previously snatched one-off')
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
else:
OComicname = oneinfo['ComicName']
OIssue = oneinfo['IssueNumber']
OPublisher = None
else:
OComicname = oneinfo['COMIC']
OIssue = oneinfo['ISSUE']
OPublisher = oneinfo['PUBLISHER']
ppinfo.append({'comicid': oneinfo['ComicID'],
'comicname': OComicname,
'issuenumber': OIssue,
'publisher': OPublisher,
'comiclocation': None,
'issueid': issueid,
'sarc': None,
'oneoff': True})
self.oneoff = True
#logger.info(module + ' Discovered %s # %s by %s [comicid:%s][issueid:%s]' % (comicname, issuenumber, publisher, comicid, issueid))
#use issueid to get publisher, series, year, issue number
else:
for x in oneoff_issuelist:
if x['One-Off'] is True:
oneinfo = myDB.selectone('SELECT * FROM weekly WHERE IssueID=?', [x['IssueID']]).fetchone()
if oneinfo is not None:
ppinfo.append({'comicid': oneinfo['ComicID'],
'comicname': oneinfo['COMIC'],
'issuenumber': oneinfo['ISSUE'],
'publisher': oneinfo['PUBLISHER'],
'issueid': x['IssueID'],
'comiclocation': x['ComicLocation'],
'sarc': None,
'oneoff': x['One-Off']})
self.oneoff = True
if len(ppinfo) > 0:
for pp in ppinfo:
logger.info('[PPINFO-POST-PROCESSING-ATTEMPT] %s' % pp)
self.nzb_or_oneoff_pp(tinfo=pp)
if any([self.nzb_name == 'Manual Run', self.issueid is not None, self.comicid is not None, self.apicall is True]):
#loop through the hits here.
if len(manual_list) == 0 and len(manual_arclist) == 0:
if self.nzb_name == 'Manual Run':
logger.info('%s No matches for Manual Run ... exiting.' % module)
if mylar.APILOCK is True:
mylar.APILOCK = False
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
elif len(manual_arclist) > 0 and len(manual_list) == 0:
logger.info('%s Manual post-processing completed for %s story-arc issues.' % (module, len(manual_arclist)))
if mylar.APILOCK is True:
mylar.APILOCK = False
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
elif len(manual_arclist) > 0:
logger.info('%s Manual post-processing completed for %s story-arc issues.' % (module, len(manual_arclist)))
i = 0
for ml in manual_list:
i+=1
comicid = ml['ComicID']
issueid = ml['IssueID']
issuenumOG = ml['IssueNumber']
#check to see if file is still being written to.
waiting = True
while waiting is True:
try:
ctime = max(os.path.getctime(ml['ComicLocation']), os.path.getmtime(ml['ComicLocation']))
if time.time() > ctime > time.time() - 10:
time.sleep(max(time.time() - ctime, 0))
else:
break
except:
#file is no longer present in location / can't be accessed.
break
dupthis = helpers.duplicate_filecheck(ml['ComicLocation'], ComicID=comicid, IssueID=issueid)
if dupthis['action'] == 'dupe_src' or dupthis['action'] == 'dupe_file':
#check if duplicate dump folder is enabled and if so move duplicate file in there for manual intervention.
#'dupe_file' - do not write new file as existing file is better quality
#'dupe_src' - write new file, as existing file is a lesser quality (dupe)
if mylar.CONFIG.DDUMP and not all([mylar.CONFIG.DUPLICATE_DUMP is None, mylar.CONFIG.DUPLICATE_DUMP == '']): #DUPLICATE_DUMP
dupchkit = self.duplicate_process(dupthis)
if dupchkit == False:
logger.warn('Unable to move duplicate file - skipping post-processing of this file.')
continue
if any([dupthis['action'] == "write", dupthis['action'] == 'dupe_src']):
stat = ' [%s/%s]' % (i, len(manual_list))
self.Process_next(comicid, issueid, issuenumOG, ml, stat)
dupthis = None
if self.failed_files == 0:
if all([self.comicid is not None, self.issueid is None]):
logger.info('%s post-processing of pack completed for %s issues.' % (module, i))
if self.issueid is not None:
if ml['AnnualType'] is not None:
logger.info('%s direct post-processing of issue completed for %s %s #%s.' % (module, ml['ComicName'], ml['AnnualType'], ml['IssueNumber']))
else:
logger.info('%s direct post-processing of issue completed for %s #%s.' % (module, ml['ComicName'], ml['IssueNumber']))
else:
logger.info('%s Manual post-processing completed for %s issues.' % (module, i))
else:
if self.comicid is not None:
logger.info('%s post-processing of pack completed for %s issues [FAILED: %s]' % (module, i, self.failed_files))
else:
logger.info('%s Manual post-processing completed for %s issues [FAILED: %s]' % (module, i, self.failed_files))
if mylar.APILOCK is True:
mylar.APILOCK = False
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
else:
pass
def nzb_or_oneoff_pp(self, tinfo=None, manual=None):
module = self.module
myDB = db.DBConnection()
manual_list = None
if tinfo is not None: #manual is None:
sandwich = None
issueid = tinfo['issueid']
comicid = tinfo['comicid']
comicname = tinfo['comicname']
issuearcid = None
issuenumber = tinfo['issuenumber']
publisher = tinfo['publisher']
sarc = tinfo['sarc']
oneoff = tinfo['oneoff']
if all([oneoff is True, tinfo['comiclocation'] is not None]):
location = os.path.abspath(os.path.join(tinfo['comiclocation'], os.pardir))
else:
location = self.nzb_folder
annchk = "no"
issuenzb = myDB.selectone("SELECT * from issues WHERE IssueID=? AND ComicName NOT NULL", [issueid]).fetchone()
if issuenzb is None:
logger.info('%s Could not detect as a standard issue - checking against annuals.' % module)
issuenzb = myDB.selectone("SELECT * from annuals WHERE IssueID=? AND ComicName NOT NULL", [issueid]).fetchone()
if issuenzb is None:
logger.info('%s issuenzb not found.' % module)
#if it's non-numeric, it contains a 'G' at the beginning indicating it's a multi-volume
#using GCD data. Set sandwich to 1 so it will bypass and continue post-processing.
if 'S' in issueid:
sandwich = issueid
if oneoff is False:
onechk = myDB.selectone('SELECT * FROM storyarcs WHERE IssueArcID=?', [re.sub('S','', issueid).strip()]).fetchone()
if onechk is not None:
issuearcid = onechk['IssueArcID']
issuenzb = myDB.selectone('SELECT * FROM issues WHERE IssueID=? AND ComicName NOT NULL', [onechk['IssueID']]).fetchone()
if issuenzb is None:
issuenzb = myDB.selectone("SELECT * from annuals WHERE IssueID=? AND ComicName NOT NULL", [onechk['IssueID']]).fetchone()
if issuenzb is not None:
issueid = issuenzb['IssueID']
logger.fdebug('Reverse lookup discovered watchlisted series [issueid: %s] - adjusting so we can PP both properly.' % issueid)
elif 'G' in issueid or '-' in issueid:
sandwich = 1
elif any([oneoff is True, issueid >= '900000', issueid == '1']):
logger.info('%s [ONE-OFF POST-PROCESSING] One-off download detected. Post-processing as a non-watchlist item.' % module)
sandwich = None #arbitrarily set it to None just to force one-off downloading below.
else:
logger.error('%s Unable to locate downloaded file as being initiated via Mylar. Attempting to parse the filename directly and process.' % module)
self._log('Unable to locate downloaded file within items I have snatched. Attempting to parse the filename directly and process.')
self.valreturn.append({"self.log": self.log,
"mode": 'outside'})
return self.queue.put(self.valreturn)
else:
logger.info('%s Successfully located issue as an annual. Continuing.' % module)
annchk = "yes"
if issuenzb is not None:
logger.info('%s issuenzb found.' % module)
if helpers.is_number(issueid):
sandwich = int(issuenzb['IssueID'])
if all([sandwich is not None, helpers.is_number(sandwich), sarc is None]):
if sandwich < 900000:
# if sandwich is less than 900000 it's a normal watchlist download. Bypass.
pass
else:
if any([oneoff is True, issuenzb is None]) or all([sandwich is not None, 'S' in str(sandwich), oneoff is True]) or int(sandwich) >= 900000:
# this has no issueID, therefore it's a one-off or a manual post-proc.
# At this point, let's just drop it into the Comic Location folder and forget about it..
if sandwich is not None and 'S' in sandwich:
self._log("One-off STORYARC mode enabled for Post-Processing for %s" % sarc)
logger.info('%s One-off STORYARC mode enabled for Post-Processing for %s' % (module, sarc))
else:
self._log("One-off mode enabled for Post-Processing. All I'm doing is moving the file untouched into the Grab-bag directory.")
if mylar.CONFIG.GRABBAG_DIR is None:
mylar.CONFIG.GRABBAG_DIR = os.path.join(mylar.CONFIG.DESTINATION_DIR, 'Grabbag')
logger.info('%s One-off mode enabled for Post-Processing. Will move into Grab-bag directory: %s' % (module, mylar.CONFIG.GRABBAG_DIR))
self._log("Grab-Bag Directory set to : %s" % mylar.CONFIG.GRABBAG_DIR)
grdst = mylar.CONFIG.GRABBAG_DIR
odir = location
if odir is None:
odir = self.nzb_folder
ofilename = orig_filename = tinfo['comiclocation']
if ofilename is not None:
path, ext = os.path.splitext(ofilename)
else:
#os.walk the location to get the filename...(coming from sab kinda thing) where it just passes the path.
for root, dirnames, filenames in os.walk(odir, followlinks=True):
for filename in filenames:
if filename.lower().endswith(self.extensions):
ofilename = orig_filename = filename
logger.fdebug('%s Valid filename located as : %s' % (module, ofilename))
path, ext = os.path.splitext(ofilename)
break
if ofilename is None:
logger.error('%s Unable to post-process file as it is not in a valid cbr/cbz format or cannot be located in path. PostProcessing aborted.' % module)
self._log('Unable to locate downloaded file to rename. PostProcessing aborted.')
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
if sandwich is not None and 'S' in sandwich:
issuearcid = re.sub('S', '', issueid)
logger.fdebug('%s issuearcid:%s' % (module, issuearcid))
arcdata = myDB.selectone("SELECT * FROM storyarcs WHERE IssueArcID=?", [issuearcid]).fetchone()
if arcdata is None:
logger.warn('%s Unable to locate issue within Story Arcs. Cannot post-process at this time - try to Refresh the Arc and manual post-process if necessary.' % module)
self._log('Unable to locate issue within Story Arcs in orde to properly assign metadata. PostProcessing aborted.')
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
if arcdata['Publisher'] is None:
arcpub = arcdata['IssuePublisher']
else:
arcpub = arcdata['Publisher']
grdst = helpers.arcformat(arcdata['StoryArc'], helpers.spantheyears(arcdata['StoryArcID']), arcpub)
if comicid is None:
comicid = arcdata['ComicID']
if comicname is None:
comicname = arcdata['ComicName']
if issuenumber is None:
issuenumber = arcdata['IssueNumber']
issueid = arcdata['IssueID']
#tag the meta.
metaresponse = None
crcvalue = helpers.crc(os.path.join(location, ofilename))
#if a one-off download from the pull-list, will not have an issueid associated with it, and will fail to due conversion/tagging.
#if altpull/2 method is being used, issueid may already be present so conversion/tagging is possible with some additional fixes.
if all([mylar.CONFIG.ENABLE_META, issueid is not None]):
self._log("Metatagging enabled - proceeding...")
try:
import cmtagmylar
metaresponse = cmtagmylar.run(location, issueid=issueid, filename=os.path.join(self.nzb_folder, ofilename))
except ImportError:
logger.warn('%s comictaggerlib not found on system. Ensure the ENTIRE lib directory is located within mylar/lib/comictaggerlib/' % module)
metaresponse = "fail"
if metaresponse == "fail":
logger.fdebug('%s Unable to write metadata successfully - check mylar.log file. Attempting to continue without metatagging...' % module)
elif any([metaresponse == "unrar error", metaresponse == "corrupt"]):
logger.error('%s This is a corrupt archive - whether CRC errors or it is incomplete. Marking as BAD, and retrying it.' %module)
#launch failed download handling here.
elif metaresponse.startswith('file not found'):
filename_in_error = metaresponse.split('||')[1]
self._log("The file cannot be found in the location provided for metatagging [%s]. Please verify it exists, and re-run if necessary." % filename_in_error)
logger.error('%s The file cannot be found in the location provided for metagging [%s]. Please verify it exists, and re-run if necessary.' % (module, filename_in_error))
else:
odir = os.path.split(metaresponse)[0]
ofilename = os.path.split(metaresponse)[1]
ext = os.path.splitext(metaresponse)[1]
logger.info('%s Sucessfully wrote metadata to .cbz (%s) - Continuing..' % (module, ofilename))
self._log('Sucessfully wrote metadata to .cbz (%s) - proceeding...' % ofilename)
dfilename = ofilename
if metaresponse:
src_location = odir
else:
src_location = location
grab_src = os.path.join(src_location, ofilename)
self._log("Source Path : %s" % grab_src)
logger.info('%s Source Path : %s' % (module, grab_src))
checkdirectory = filechecker.validateAndCreateDirectory(grdst, True, module=module)
if not checkdirectory:
logger.warn('%s Error trying to validate/create directory. Aborting this process at this time.' % module)
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
#send to renamer here if valid.
if mylar.CONFIG.RENAME_FILES:
renamed_file = helpers.rename_param(comicid, comicname, issuenumber, dfilename, issueid=issueid, arc=sarc)
if renamed_file:
dfilename = renamed_file['nfilename']
logger.fdebug('%s Renaming file to conform to configuration: %s' % (module, dfilename))
if sandwich is not None and 'S' in sandwich:
#if from a StoryArc, check to see if we're appending the ReadingOrder to the filename
if mylar.CONFIG.READ2FILENAME:
logger.fdebug('%s readingorder#: %s' % (module, arcdata['ReadingOrder']))
if int(arcdata['ReadingOrder']) < 10: readord = "00" + str(arcdata['ReadingOrder'])
elif int(arcdata['ReadingOrder']) >= 10 and int(arcdata['ReadingOrder']) <= 99: readord = "0" + str(arcdata['ReadingOrder'])
else: readord = str(arcdata['ReadingOrder'])
dfilename = str(readord) + "-" + dfilename
else:
dfilename = ofilename
grab_dst = os.path.join(grdst, dfilename)
else:
grab_dst = os.path.join(grdst, dfilename)
if not os.path.exists(grab_dst) or grab_src == grab_dst:
#if it hits this, ofilename is the full path so we need to extract just the filename to path it back to a possible grab_bag dir
grab_dst = os.path.join(grdst, os.path.split(dfilename)[1])
self._log("Destination Path : %s" % grab_dst)
logger.info('%s Destination Path : %s' % (module, grab_dst))
logger.info('%s[%s] %s into directory : %s' % (module, mylar.CONFIG.FILE_OPTS, ofilename, grab_dst))
try:
checkspace = helpers.get_free_space(grdst)
if checkspace is False:
if all([metaresponse != 'fail', metaresponse is not None]): # meta was done
self.tidyup(src_location, True, cacheonly=True)
raise OSError
fileoperation = helpers.file_ops(grab_src, grab_dst)
if not fileoperation:
raise OSError
except Exception as e:
logger.error('%s Failed to %s %s: %s' % (module, mylar.CONFIG.FILE_OPTS, grab_src, e))
self._log("Failed to %s %s: %s" % (mylar.CONFIG.FILE_OPTS, grab_src, e))
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
#tidyup old path
if any([mylar.CONFIG.FILE_OPTS == 'move', mylar.CONFIG.FILE_OPTS == 'copy']):
self.tidyup(src_location, True, filename=orig_filename)
#delete entry from nzblog table
myDB.action('DELETE from nzblog WHERE issueid=?', [issueid])
if sandwich is not None and 'S' in sandwich:
logger.info('%s IssueArcID is : %s' % (module, issuearcid))
ctrlVal = {"IssueArcID": issuearcid}
newVal = {"Status": "Downloaded",
"Location": grab_dst}
myDB.upsert("storyarcs", newVal, ctrlVal)
logger.info('%s Updated status to Downloaded' % module)
logger.info('%s Post-Processing completed for: [%s] %s' % (module, sarc, grab_dst))
self._log(u"Post Processing SUCCESSFUL! ")
elif oneoff is True:
logger.info('%s IssueID is : %s' % (module, issueid))
ctrlVal = {"IssueID": issueid}
newVal = {"Status": "Downloaded"}
logger.info('%s Writing to db: %s -- %s' % (module, newVal, ctrlVal))
myDB.upsert("weekly", newVal, ctrlVal)
logger.info('%s Updated status to Downloaded' % module)
myDB.upsert("oneoffhistory", newVal, ctrlVal)
logger.info('%s Updated history for one-off\'s for tracking purposes' % module)
logger.info('%s Post-Processing completed for: [ %s #%s ] %s' % (module, comicname, issuenumber, grab_dst))
self._log(u"Post Processing SUCCESSFUL! ")
imageUrl = myDB.select('SELECT ImageURL from issues WHERE IssueID=?', [issueid])
if imageUrl:
imageUrl = imageUrl[0][0]
try:
self.sendnotify(comicname, issueyear=None, issuenumOG=issuenumber, annchk=annchk, module=module, imageUrl=imageUrl)
except:
pass
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
else:
try:
len(manual_arclist)
except:
manual_arclist = []
if tinfo['comiclocation'] is None:
cloc = self.nzb_folder
else:
cloc = tinfo['comiclocation']
clocation = cloc
if os.path.isdir(cloc):
for root, dirnames, filenames in os.walk(cloc, followlinks=True):
for filename in filenames:
if filename.lower().endswith(self.extensions):
clocation = os.path.join(root, filename)
manual_list = {'ComicID': tinfo['comicid'],
'IssueID': tinfo['issueid'],
'ComicLocation': clocation,
'SARC': tinfo['sarc'],
'IssueArcID': issuearcid,
'ComicName': tinfo['comicname'],
'IssueNumber': tinfo['issuenumber'],
'Publisher': tinfo['publisher'],
'OneOff': tinfo['oneoff'],
'ForcedMatch': False}
else:
manual_list = manual
if self.nzb_name == 'Manual Run':
#loop through the hits here.
if len(manual_list) == 0 and len(manual_arclist) == 0:
logger.info('%s No matches for Manual Run ... exiting.' % module)
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
elif len(manual_arclist) > 0 and len(manual_list) == 0:
logger.info('%s Manual post-processing completed for %s story-arc issues.' % (module, len(manual_arclist)))
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
elif len(manual_arclist) > 0:
logger.info('%s Manual post-processing completed for %s story-arc issues.' % (module, len(manual_arclist)))
i = 0
for ml in manual_list:
i+=1
comicid = ml['ComicID']
issueid = ml['IssueID']
issuenumOG = ml['IssueNumber']
#check to see if file is still being written to.
while True:
waiting = False
try:
ctime = max(os.path.getctime(ml['ComicLocation']), os.path.getmtime(ml['ComicLocation']))
if time.time() > ctime > time.time() - 10:
time.sleep(max(time.time() - ctime, 0))
waiting = True
else:
break
except:
#file is no longer present in location / can't be accessed.
break
dupthis = helpers.duplicate_filecheck(ml['ComicLocation'], ComicID=comicid, IssueID=issueid)
if dupthis['action'] == 'dupe_src' or dupthis['action'] == 'dupe_file':
#check if duplicate dump folder is enabled and if so move duplicate file in there for manual intervention.
#'dupe_file' - do not write new file as existing file is better quality
#check if duplicate dump folder is enabled and if so move duplicate file in there for manual intervention.
#'dupe_file' - do not write new file as existing file is better quality
#'dupe_src' - write new file, as existing file is a lesser quality (dupe)
if mylar.CONFIG.DDUMP and not all([mylar.CONFIG.DUPLICATE_DUMP is None, mylar.CONFIG.DUPLICATE_DUMP == '']): #DUPLICATE_DUMP
dupchkit = self.duplicate_process(dupthis)
if dupchkit == False:
logger.warn('Unable to move duplicate file - skipping post-processing of this file.')
continue
if any([dupthis['action'] == "write", dupthis['action'] == 'dupe_src']):
stat = ' [%s/%s]' % (i, len(manual_list))
self.Process_next(comicid, issueid, issuenumOG, ml, stat)
dupthis = None
if self.failed_files == 0:
logger.info('%s Manual post-processing completed for %s issues.' % (module, i))
else:
logger.info('%s Manual post-processing completed for %s issues [FAILED: %s]' % (module, i, self.failed_files))
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
else:
comicid = issuenzb['ComicID']
issuenumOG = issuenzb['Issue_Number']
#the self.nzb_folder should contain only the existing filename
dupthis = helpers.duplicate_filecheck(self.nzb_folder, ComicID=comicid, IssueID=issueid)
if dupthis['action'] == 'dupe_src' or dupthis['action'] == 'dupe_file':
#check if duplicate dump folder is enabled and if so move duplicate file in there for manual intervention.
#'dupe_file' - do not write new file as existing file is better quality
#'dupe_src' - write new file, as existing file is a lesser quality (dupe)
if mylar.CONFIG.DUPLICATE_DUMP:
if mylar.CONFIG.DDUMP and not all([mylar.CONFIG.DUPLICATE_DUMP is None, mylar.CONFIG.DUPLICATE_DUMP == '']):
dupchkit = self.duplicate_process(dupthis)
if dupchkit == False:
logger.warn('Unable to move duplicate file - skipping post-processing of this file.')
self.valreturn.append({"self.log": self.log,
"mode": 'stop',
"issueid": issueid,
"comicid": comicid})
return self.queue.put(self.valreturn)
if dupthis['action'] == "write" or dupthis['action'] == 'dupe_src':
if manual_list is None:
return self.Process_next(comicid, issueid, issuenumOG)
else:
logger.info('Post-processing issue is found in more than one destination - let us do this!')
return self.Process_next(comicid, issueid, issuenumOG, manual_list)
else:
self.valreturn.append({"self.log": self.log,
"mode": 'stop',
"issueid": issueid,
"comicid": comicid})
return self.queue.put(self.valreturn)
def Process_next(self, comicid, issueid, issuenumOG, ml=None, stat=None):
if stat is None: stat = ' [1/1]'
module = self.module
annchk = "no"
snatchedtorrent = False
myDB = db.DBConnection()
comicnzb = myDB.selectone("SELECT * from comics WHERE comicid=?", [comicid]).fetchone()
issuenzb = myDB.selectone("SELECT * from issues WHERE issueid=? AND comicid=? AND ComicName NOT NULL", [issueid, comicid]).fetchone()
if ml is not None and mylar.CONFIG.SNATCHEDTORRENT_NOTIFY:
snatchnzb = myDB.selectone("SELECT * from snatched WHERE IssueID=? AND ComicID=? AND (provider=? OR provider=? OR provider=? OR provider=?) AND Status='Snatched'", [issueid, comicid, 'TPSE', 'DEM', 'WWT', '32P']).fetchone()
if snatchnzb is None:
logger.fdebug('%s Was not snatched as a torrent. Using manual post-processing.' % module)
else:
logger.fdebug('%s Was downloaded from %s. Enabling torrent manual post-processing completion notification.' % (module, snatchnzb['Provider']))
if issuenzb is None:
issuenzb = myDB.selectone("SELECT * from annuals WHERE issueid=? and comicid=?", [issueid, comicid]).fetchone()
annchk = "yes"
if annchk == "no":
logger.info('%s %s Starting Post-Processing for %s issue: %s' % (module, stat, issuenzb['ComicName'], issuenzb['Issue_Number']))
else:
logger.info('%s %s Starting Post-Processing for %s issue: %s' % (module, stat, issuenzb['ReleaseComicName'], issuenzb['Issue_Number']))
logger.fdebug('%s issueid: %s' % (module, issueid))
logger.fdebug('%s issuenumOG: %s' % (module, issuenumOG))
#issueno = str(issuenum).split('.')[0]
#new CV API - removed all decimals...here we go AGAIN!
issuenum = issuenzb['Issue_Number']
issue_except = 'None'
if 'au' in issuenum.lower() and issuenum[:1].isdigit():
issuenum = re.sub("[^0-9]", "", issuenum)
issue_except = ' AU'
elif 'ai' in issuenum.lower() and issuenum[:1].isdigit():
issuenum = re.sub("[^0-9]", "", issuenum)
issue_except = ' AI'
elif 'inh' in issuenum.lower() and issuenum[:1].isdigit():
issuenum = re.sub("[^0-9]", "", issuenum)
issue_except = '.INH'
elif 'now' in issuenum.lower() and issuenum[:1].isdigit():
if '!' in issuenum: issuenum = re.sub('\!', '', issuenum)
issuenum = re.sub("[^0-9]", "", issuenum)
issue_except = '.NOW'
elif 'mu' in issuenum.lower() and issuenum[:1].isdigit():
issuenum = re.sub("[^0-9]", "", issuenum)
issue_except = '.MU'
elif 'hu' in issuenum.lower() and issuenum[:1].isdigit():
issuenum = re.sub("[^0-9]", "", issuenum)
issue_except = '.HU'
elif u'\xbd' in issuenum:
issuenum = '0.5'
elif u'\xbc' in issuenum:
issuenum = '0.25'
elif u'\xbe' in issuenum:
issuenum = '0.75'
elif u'\u221e' in issuenum:
#issnum = utf-8 will encode the infinity symbol without any help
issuenum = 'infinity'
else:
issue_exceptions = ['A',
'B',
'C',
'X',
'O']
exceptionmatch = [x for x in issue_exceptions if x.lower() in issuenum.lower()]
if exceptionmatch:
logger.fdebug('[FILECHECKER] We matched on : ' + str(exceptionmatch))
for x in exceptionmatch:
issuenum = re.sub("[^0-9]", "", issuenum)
issue_except = x
if '.' in issuenum:
iss_find = issuenum.find('.')
iss_b4dec = issuenum[:iss_find]
if iss_b4dec == '':
iss_b4dec = '0'
iss_decval = issuenum[iss_find +1:]
if iss_decval.endswith('.'): iss_decval = iss_decval[:-1]
if int(iss_decval) == 0:
iss = iss_b4dec
issdec = int(iss_decval)
issueno = str(iss)
self._log("Issue Number: %s" % issueno)
logger.fdebug('%s Issue Number: %s' % (module, issueno))
else:
if len(iss_decval) == 1:
iss = iss_b4dec + "." + iss_decval
issdec = int(iss_decval) * 10
else:
iss = iss_b4dec + "." + iss_decval.rstrip('0')
issdec = int(iss_decval.rstrip('0')) * 10
issueno = iss_b4dec
self._log("Issue Number: %s" % iss)
logger.fdebug('%s Issue Number: %s' % (module, iss))
else:
iss = issuenum
issueno = iss
# issue zero-suppression here
if mylar.CONFIG.ZERO_LEVEL == "0":
zeroadd = ""
else:
if mylar.CONFIG.ZERO_LEVEL_N == "none": zeroadd = ""
elif mylar.CONFIG.ZERO_LEVEL_N == "0x": zeroadd = "0"
elif mylar.CONFIG.ZERO_LEVEL_N == "00x": zeroadd = "00"
logger.fdebug('%s Zero Suppression set to : %s' % (module, mylar.CONFIG.ZERO_LEVEL_N))
prettycomiss = None
if issueno.isalpha():
logger.fdebug('issue detected as an alpha.')
prettycomiss = str(issueno)
else:
try:
x = float(issueno)
#validity check
if x < 0:
logger.info('%s I\'ve encountered a negative issue #: %s. Trying to accomodate' % (module, issueno))
prettycomiss = '-%s%s' % (zeroadd, issueno[1:])
elif x >= 0:
pass
else:
raise ValueError
except ValueError, e:
logger.warn('Unable to properly determine issue number [%s] - you should probably log this on github for help.' % issueno)
return
if prettycomiss is None and len(str(issueno)) > 0:
#if int(issueno) < 0:
# self._log("issue detected is a negative")
# prettycomiss = '-' + str(zeroadd) + str(abs(issueno))
if int(issueno) < 10:
logger.fdebug('issue detected less than 10')
if '.' in iss:
if int(iss_decval) > 0:
issueno = str(iss)
prettycomiss = str(zeroadd) + str(iss)
else:
prettycomiss = str(zeroadd) + str(int(issueno))
else:
prettycomiss = str(zeroadd) + str(iss)
if issue_except != 'None':
prettycomiss = str(prettycomiss) + issue_except
logger.fdebug('%s Zero level supplement set to %s. Issue will be set as : %s' % (module, mylar.CONFIG.ZERO_LEVEL_N, prettycomiss))
elif int(issueno) >= 10 and int(issueno) < 100:
logger.fdebug('issue detected greater than 10, but less than 100')
if mylar.CONFIG.ZERO_LEVEL_N == "none":
zeroadd = ""
else:
zeroadd = "0"
if '.' in iss:
if int(iss_decval) > 0:
issueno = str(iss)
prettycomiss = str(zeroadd) + str(iss)
else:
prettycomiss = str(zeroadd) + str(int(issueno))
else:
prettycomiss = str(zeroadd) + str(iss)
if issue_except != 'None':
prettycomiss = str(prettycomiss) + issue_except
logger.fdebug('%s Zero level supplement set to %s. Issue will be set as : %s' % (module, mylar.CONFIG.ZERO_LEVEL_N, prettycomiss))
else:
logger.fdebug('issue detected greater than 100')
if '.' in iss:
if int(iss_decval) > 0:
issueno = str(iss)
prettycomiss = str(issueno)
if issue_except != 'None':
prettycomiss = str(prettycomiss) + issue_except
logger.fdebug('%s Zero level supplement set to %s. Issue will be set as : %s' % (module, mylar.CONFIG.ZERO_LEVEL_N, prettycomiss))
elif len(str(issueno)) == 0:
prettycomiss = str(issueno)
logger.fdebug('issue length error - cannot determine length. Defaulting to None: %s ' % prettycomiss)
if annchk == "yes":
self._log("Annual detected.")
logger.fdebug('%s Pretty Comic Issue is : %s' % (module, prettycomiss))
issueyear = issuenzb['IssueDate'][:4]
self._log("Issue Year: %s" % issueyear)
logger.fdebug('%s Issue Year : %s' % (module, issueyear))
month = issuenzb['IssueDate'][5:7].replace('-', '').strip()
month_name = helpers.fullmonth(month)
if month_name is None:
month_name = 'None'
publisher = comicnzb['ComicPublisher']
self._log("Publisher: %s" % publisher)
logger.fdebug('%s Publisher: %s' % (module, publisher))
#we need to un-unicode this to make sure we can write the filenames properly for spec.chars
series = comicnzb['ComicName'].encode('ascii', 'ignore').strip()
self._log("Series: %s" % series)
logger.fdebug('%s Series: %s' % (module, series))
if comicnzb['AlternateFileName'] is None or comicnzb['AlternateFileName'] == 'None':
seriesfilename = series
else:
seriesfilename = comicnzb['AlternateFileName'].encode('ascii', 'ignore').strip()
logger.fdebug('%s Alternate File Naming has been enabled for this series. Will rename series to : %s' % (module, seriesfilename))
seriesyear = comicnzb['ComicYear']
self._log("Year: %s" % seriesyear)
logger.fdebug('%s Year: %s' % (module, seriesyear))
comlocation = comicnzb['ComicLocation']
self._log("Comic Location: %s" % comlocation)
logger.fdebug('%s Comic Location: %s' % (module, comlocation))
comversion = comicnzb['ComicVersion']
self._log("Comic Version: %s" % comversion)
logger.fdebug('%s Comic Version: %s' % (module, comversion))
if comversion is None:
comversion = 'None'
#if comversion is None, remove it so it doesn't populate with 'None'
if comversion == 'None':
chunk_f_f = re.sub('\$VolumeN', '', mylar.CONFIG.FILE_FORMAT)
chunk_f = re.compile(r'\s+')
chunk_file_format = chunk_f.sub(' ', chunk_f_f)
self._log("No version # found for series - tag will not be available for renaming.")
logger.fdebug('%s No version # found for series, removing from filename' % module)
logger.fdebug('%s New format is now: %s' % (module, chunk_file_format))
else:
chunk_file_format = mylar.CONFIG.FILE_FORMAT
if annchk == "no":
chunk_f_f = re.sub('\$Annual', '', chunk_file_format)
chunk_f = re.compile(r'\s+')
chunk_file_format = chunk_f.sub(' ', chunk_f_f)
logger.fdebug('%s Not an annual - removing from filename parameters' % module)
logger.fdebug('%s New format: %s' % (module, chunk_file_format))
else:
logger.fdebug('%s Chunk_file_format is: %s' % (module, chunk_file_format))
if '$Annual' not in chunk_file_format:
#if it's an annual, but $Annual isn't specified in file_format, we need to
#force it in there, by default in the format of $Annual $Issue
prettycomiss = "Annual %s" % prettycomiss
logger.fdebug('%s prettycomiss: %s' % (module, prettycomiss))
ofilename = None
#if it's a Manual Run, use the ml['ComicLocation'] for the exact filename.
if ml is None:
importissue = False
for root, dirnames, filenames in os.walk(self.nzb_folder, followlinks=True):
for filename in filenames:
if filename.lower().endswith(self.extensions):
odir = root
logger.fdebug('%s odir (root): %s' % (module, odir))
ofilename = filename
logger.fdebug('%s ofilename: %s' % (module, ofilename))
path, ext = os.path.splitext(ofilename)
try:
if odir is None:
logger.fdebug('%s No root folder set.' % module)
odir = self.nzb_folder
except:
logger.error('%s unable to set root folder. Forcing it due to some error above most likely.' % module)
if os.path.isfile(self.nzb_folder) and self.nzb_folder.lower().endswith(self.extensions):
import ntpath
odir, ofilename = ntpath.split(self.nzb_folder)
path, ext = os.path.splitext(ofilename)
importissue = True
else:
odir = self.nzb_folder
if ofilename is None:
self._log("Unable to locate a valid cbr/cbz file. Aborting post-processing for this filename.")
logger.error('%s unable to locate a valid cbr/cbz file. Aborting post-processing for this filename.' % module)
self.failed_files +=1
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
logger.fdebug('%s odir: %s' % (module, odir))
logger.fdebug('%s ofilename: %s' % (module, ofilename))
#if meta-tagging is not enabled, we need to declare the check as being fail
#if meta-tagging is enabled, it gets changed just below to a default of pass
pcheck = "fail"
#make sure we know any sub-folder off of self.nzb_folder that is being used so when we do
#tidy-up we can remove the empty directory too. odir is the original COMPLETE path at this point
if ml is None:
subpath = odir
orig_filename = ofilename
crcvalue = helpers.crc(os.path.join(odir, ofilename))
else:
subpath, orig_filename = os.path.split(ml['ComicLocation'])
crcvalue = helpers.crc(ml['ComicLocation'])
#tag the meta.
if mylar.CONFIG.ENABLE_META:
self._log("Metatagging enabled - proceeding...")
logger.fdebug('%s Metatagging enabled - proceeding...' % module)
pcheck = "pass"
if mylar.CONFIG.CMTAG_START_YEAR_AS_VOLUME:
vol_label = seriesyear
else:
vol_label = comversion
try:
import cmtagmylar
if ml is None:
pcheck = cmtagmylar.run(self.nzb_folder, issueid=issueid, comversion=vol_label, filename=os.path.join(odir, ofilename))
else:
pcheck = cmtagmylar.run(self.nzb_folder, issueid=issueid, comversion=vol_label, manual="yes", filename=ml['ComicLocation'])
except ImportError:
logger.fdebug('%s comictaggerlib not found on system. Ensure the ENTIRE lib directory is located within mylar/lib/comictaggerlib/' % module)
logger.fdebug('%s continuing with PostProcessing, but I am not using metadata.' % module)
pcheck = "fail"
if pcheck == "fail":
self._log("Unable to write metadata successfully - check mylar.log file. Attempting to continue without tagging...")
logger.fdebug('%s Unable to write metadata successfully - check mylar.log file. Attempting to continue without tagging...' %module)
self.failed_files +=1
#we need to set this to the cbz file since not doing it will result in nothing getting moved.
#not sure how to do this atm
elif any([pcheck == "unrar error", pcheck == "corrupt"]):
if ml is not None:
self._log("This is a corrupt archive - whether CRC errors or it's incomplete. Marking as BAD, and not post-processing.")
logger.error('%s This is a corrupt archive - whether CRC errors or it is incomplete. Marking as BAD, and not post-processing.' % module)
self.failed_files +=1
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
else:
self._log("This is a corrupt archive - whether CRC errors or it's incomplete. Marking as BAD, and retrying a different copy.")
logger.error('%s This is a corrupt archive - whether CRC errors or it is incomplete. Marking as BAD, and retrying a different copy.' % module)
self.valreturn.append({"self.log": self.log,
"mode": 'fail',
"issueid": issueid,
"comicid": comicid,
"comicname": comicnzb['ComicName'],
"issuenumber": issuenzb['Issue_Number'],
"annchk": annchk})
return self.queue.put(self.valreturn)
elif pcheck.startswith('file not found'):
filename_in_error = pcheck.split('||')[1]
self._log("The file cannot be found in the location provided [%s]. Please verify it exists, and re-run if necessary. Aborting." % filename_in_error)
logger.error('%s The file cannot be found in the location provided [%s]. Please verify it exists, and re-run if necessary. Aborting' % (module, filename_in_error))
self.failed_files +=1
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
else:
#need to set the filename source as the new name of the file returned from comictagger.
odir = os.path.split(pcheck)[0]
ofilename = os.path.split(pcheck)[1]
ext = os.path.splitext(ofilename)[1]
self._log("Sucessfully wrote metadata to .cbz - Continuing..")
logger.info('%s Sucessfully wrote metadata to .cbz (%s) - Continuing..' % (module, ofilename))
#Run Pre-script
if mylar.CONFIG.ENABLE_PRE_SCRIPTS:
nzbn = self.nzb_name #original nzb name
nzbf = self.nzb_folder #original nzb folder
#name, comicyear, comicid , issueid, issueyear, issue, publisher
#create the dic and send it.
seriesmeta = []
seriesmetadata = {}
seriesmeta.append({
'name': series,
'comicyear': seriesyear,
'comicid': comicid,
'issueid': issueid,
'issueyear': issueyear,
'issue': issuenum,
'publisher': publisher
})
seriesmetadata['seriesmeta'] = seriesmeta
self._run_pre_scripts(nzbn, nzbf, seriesmetadata)
file_values = {'$Series': seriesfilename,
'$Issue': prettycomiss,
'$Year': issueyear,
'$series': series.lower(),
'$Publisher': publisher,
'$publisher': publisher.lower(),
'$VolumeY': 'V' + str(seriesyear),
'$VolumeN': comversion,
'$monthname': month_name,
'$month': month,
'$Annual': 'Annual'
}
if ml:
if pcheck == "fail":
odir, ofilename = os.path.split(ml['ComicLocation'])
orig_filename = ofilename
elif pcheck:
#odir, ofilename already set. Carry it through.
pass
else:
odir, orig_filename = os.path.split(ml['ComicLocation'])
logger.fdebug('%s ofilename: %s' % (module, ofilename))
if any([ofilename == odir, ofilename == odir[:-1], ofilename == '']):
self._log("There was a problem deciphering the filename/directory - please verify that the filename : [%s] exists in location [%s]. Aborting." % (ofilename, odir))
logger.error(module + ' There was a problem deciphering the filename/directory - please verify that the filename : [%s] exists in location [%s]. Aborting.' % (ofilename, odir))
self.failed_files +=1
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
logger.fdebug('%s odir: %s' % (module, odir))
logger.fdebug('%s ofilename: %s' % (module, ofilename))
ext = os.path.splitext(ofilename)[1]
logger.fdebug('%s ext: %s' % (module, ext))
if ofilename is None or ofilename == '':
logger.error('%s Aborting PostProcessing - the filename does not exist in the location given. Make sure that %s exists and is the correct location.' % (module, self.nzb_folder))
self.failed_files +=1
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
self._log('Original Filename: %s [%s]' % (orig_filename, ext))
logger.fdebug('%s Original Filename: %s [%s]' % (module, orig_filename, ext))
if mylar.CONFIG.FILE_FORMAT == '' or not mylar.CONFIG.RENAME_FILES:
self._log("Rename Files isn't enabled...keeping original filename.")
logger.fdebug('%s Rename Files is not enabled - keeping original filename.' % module)
#check if extension is in nzb_name - will screw up otherwise
if ofilename.lower().endswith(self.extensions):
nfilename = ofilename[:-4]
else:
nfilename = ofilename
else:
nfilename = helpers.replace_all(chunk_file_format, file_values)
if mylar.CONFIG.REPLACE_SPACES:
#mylar.CONFIG.REPLACE_CHAR ...determines what to replace spaces with underscore or dot
nfilename = nfilename.replace(' ', mylar.CONFIG.REPLACE_CHAR)
nfilename = re.sub('[\,\:\?\"\']', '', nfilename)
nfilename = re.sub('[\/\*]', '-', nfilename)
if ml is not None and ml['ForcedMatch'] is True:
xyb = nfilename.find('[__')
if xyb != -1:
yyb = nfilename.find('__]', xyb)
if yyb != -1:
rem_issueid = nfilename[xyb+3:yyb]
logger.fdebug('issueid: %s' % rem_issueid)
nfilename = '%s %s'.strip() % (nfilename[:xyb], nfilename[yyb+3:])
logger.fdebug('issueid information [%s] removed successfully: %s' % (rem_issueid, nfilename))
self._log("New Filename: %s" % nfilename)
logger.fdebug('%s New Filename: %s' % (module, nfilename))
src = os.path.join(odir, ofilename)
checkdirectory = filechecker.validateAndCreateDirectory(comlocation, True, module=module)
if not checkdirectory:
logger.warn('%s Error trying to validate/create directory. Aborting this process at this time.' % module)
self.failed_files +=1
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
if mylar.CONFIG.LOWERCASE_FILENAMES:
dst = os.path.join(comlocation, (nfilename + ext).lower())
else:
dst = os.path.join(comlocation, (nfilename + ext.lower()))
self._log("Source: %s" % src)
self._log("Destination: %s" % dst)
logger.fdebug('%s Source: %s' % (module, src))
logger.fdebug('%s Destination: %s' % (module, dst))
if ml is None:
#downtype = for use with updater on history table to set status to 'Downloaded'
downtype = 'True'
#non-manual run moving/deleting...
logger.fdebug('%s self.nzb_folder: %s' % (module, self.nzb_folder))
logger.fdebug('%s odir: %s' % (module, odir))
logger.fdebug('%s ofilename: %s' % (module, ofilename))
logger.fdebug('%s nfilename: %s' % (module, nfilename + ext))
if mylar.CONFIG.RENAME_FILES:
if ofilename != (nfilename + ext):
logger.fdebug('%s Renaming %s ..to.. %s' % (module, os.path.join(odir, ofilename), os.path.join(odir, nfilename + ext)))
else:
logger.fdebug('%s Filename is identical as original, not renaming.' % module)
src = os.path.join(odir, ofilename)
try:
self._log("[%s] %s - to - %s" % (mylar.CONFIG.FILE_OPTS, src, dst))
checkspace = helpers.get_free_space(comlocation)
if checkspace is False:
if all([pcheck is not None, pcheck != 'fail']): # meta was done
self.tidyup(odir, True, cacheonly=True)
raise OSError
fileoperation = helpers.file_ops(src, dst)
if not fileoperation:
raise OSError
except Exception as e:
self._log("Failed to %s %s - check log for exact error." % (mylar.CONFIG.FILE_OPTS, src))
self._log("Post-Processing ABORTED.")
logger.error('%s Failed to %s %s: %s' % (module, mylar.CONFIG.FILE_OPTS, src, e))
logger.error('%s Post-Processing ABORTED' % module)
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
#tidyup old path
if any([mylar.CONFIG.FILE_OPTS == 'move', mylar.CONFIG.FILE_OPTS == 'copy']):
self.tidyup(odir, True, filename=orig_filename)
else:
#downtype = for use with updater on history table to set status to 'Post-Processed'
downtype = 'PP'
#Manual Run, this is the portion.
src = os.path.join(odir, ofilename)
if mylar.CONFIG.RENAME_FILES:
if ofilename != (nfilename + ext):
logger.fdebug('%s Renaming %s ..to.. %s' % (module, os.path.join(odir, ofilename), os.path.join(odir, self.nzb_folder, str(nfilename + ext))))
else:
logger.fdebug('%s Filename is identical as original, not renaming.' % module)
logger.fdebug('%s odir src : %s' % (module, src))
logger.fdebug('%s[%s] %s ... to ... %s' % (module, mylar.CONFIG.FILE_OPTS, src, dst))
try:
checkspace = helpers.get_free_space(comlocation)
if checkspace is False:
if all([pcheck != 'fail', pcheck is not None]): # meta was done
self.tidyup(odir, True, cacheonly=True)
raise OSError
fileoperation = helpers.file_ops(src, dst)
if not fileoperation:
raise OSError
except Exception as e:
logger.error('%s Failed to %s %s: %s' % (module, mylar.CONFIG.FILE_OPTS, src, e))
logger.error('%s Post-Processing ABORTED.' %module)
self.failed_files +=1
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
logger.info('%s %s successful to : %s' % (module, mylar.CONFIG.FILE_OPTS, dst))
if any([mylar.CONFIG.FILE_OPTS == 'move', mylar.CONFIG.FILE_OPTS == 'copy']):
self.tidyup(odir, True, subpath, filename=orig_filename)
#Hopefully set permissions on downloaded file
if mylar.CONFIG.ENFORCE_PERMS:
if mylar.OS_DETECT != 'windows':
filechecker.setperms(dst.rstrip())
else:
try:
permission = int(mylar.CONFIG.CHMOD_FILE, 8)
os.umask(0)
os.chmod(dst.rstrip(), permission)
except OSError:
logger.error('%s Failed to change file permissions. Ensure that the user running Mylar has proper permissions to change permissions in : %s' % (module, dst))
logger.fdebug('%s Continuing post-processing but unable to change file permissions in %s' % (module, dst))
#let's reset the fileop to the original setting just in case it's a manual pp run
if mylar.CONFIG.FILE_OPTS == 'copy':
self.fileop = shutil.copy
else:
self.fileop = shutil.move
#delete entry from nzblog table
myDB.action('DELETE from nzblog WHERE issueid=?', [issueid])
updater.totals(comicid, havefiles='+1',issueid=issueid,file=dst)
#update snatched table to change status to Downloaded
if annchk == "no":
updater.foundsearch(comicid, issueid, down=downtype, module=module, crc=crcvalue)
dispiss = '#%s' % issuenumOG
updatetable = 'issues'
else:
updater.foundsearch(comicid, issueid, mode='want_ann', down=downtype, module=module, crc=crcvalue)
if 'annual' in issuenzb['ReleaseComicName'].lower(): #series.lower():
dispiss = 'Annual #%s' % issuenumOG
elif 'special' in issuenzb['ReleaseComicName'].lower():
dispiss = 'Special #%s' % issuenumOG
else:
dispiss = '#%s' % issuenumOG
updatetable = 'annuals'
logger.fdebug('[annchk:%s] issue to update: %s' % (annchk, dispiss))
#new method for updating status after pp
if os.path.isfile(dst):
ctrlVal = {"IssueID": issueid}
newVal = {"Status": "Downloaded",
"Location": os.path.basename(dst)}
logger.fdebug('writing: %s -- %s' % (newVal, ctrlVal))
myDB.upsert(updatetable, newVal, ctrlVal)
try:
if ml['IssueArcID']:
logger.info('Watchlist Story Arc match detected.')
logger.info(ml)
arcinfo = myDB.selectone('SELECT * FROM storyarcs where IssueArcID=?', [ml['IssueArcID']]).fetchone()
if arcinfo is None:
logger.warn('Unable to locate IssueID within givin Story Arc. Ensure everything is up-to-date (refreshed) for the Arc.')
else:
if mylar.CONFIG.COPY2ARCDIR is True:
if arcinfo['Publisher'] is None:
arcpub = arcinfo['IssuePublisher']
else:
arcpub = arcinfo['Publisher']
grdst = helpers.arcformat(arcinfo['StoryArc'], helpers.spantheyears(arcinfo['StoryArcID']), arcpub)
logger.info('grdst:' + grdst)
checkdirectory = filechecker.validateAndCreateDirectory(grdst, True, module=module)
if not checkdirectory:
logger.warn('%s Error trying to validate/create directory. Aborting this process at this time.' % module)
self.valreturn.append({"self.log": self.log,
"mode": 'stop'})
return self.queue.put(self.valreturn)
if mylar.CONFIG.READ2FILENAME:
logger.fdebug('%s readingorder#: %s' % (module, arcinfo['ReadingOrder']))
if int(arcinfo['ReadingOrder']) < 10: readord = "00" + str(arcinfo['ReadingOrder'])
elif int(arcinfo['ReadingOrder']) >= 10 and int(arcinfo['ReadingOrder']) <= 99: readord = "0" + str(arcinfo['ReadingOrder'])
else: readord = str(arcinfo['ReadingOrder'])
dfilename = str(readord) + "-" + os.path.split(dst)[1]
else:
dfilename = os.path.split(dst)[1]
grab_dst = os.path.join(grdst, dfilename)
logger.fdebug('%s Destination Path : %s' % (module, grab_dst))
grab_src = dst
logger.fdebug('%s Source Path : %s' % (module, grab_src))
logger.info('%s[%s] %s into directory: %s' % (module, mylar.CONFIG.ARC_FILEOPS.upper(), dst, grab_dst))
try:
#need to ensure that src is pointing to the series in order to do a soft/hard-link properly
checkspace = helpers.get_free_space(grdst)
if checkspace is False:
raise OSError
fileoperation = helpers.file_ops(grab_src, grab_dst, arc=True)
if not fileoperation:
raise OSError
except Exception as e:
logger.error('%s Failed to %s %s: %s' % (module, mylar.CONFIG.ARC_FILEOPS, grab_src, e))
return
else:
grab_dst = dst
#delete entry from nzblog table in case it was forced via the Story Arc Page
IssArcID = 'S' + str(ml['IssueArcID'])
myDB.action('DELETE from nzblog WHERE IssueID=? AND SARC=?', [IssArcID,arcinfo['StoryArc']])
logger.fdebug('%s IssueArcID: %s' % (module, ml['IssueArcID']))
ctrlVal = {"IssueArcID": ml['IssueArcID']}
newVal = {"Status": "Downloaded",
"Location": grab_dst}
logger.fdebug('writing: %s -- %s' % (newVal, ctrlVal))
myDB.upsert("storyarcs", newVal, ctrlVal)
logger.fdebug('%s [%s] Post-Processing completed for: %s' % (module, arcinfo['StoryArc'], grab_dst))
except:
pass
if mylar.CONFIG.WEEKFOLDER or mylar.CONFIG.SEND2READ:
#mylar.CONFIG.WEEKFOLDER = will *copy* the post-processed file to the weeklypull list folder for the given week.
#mylar.CONFIG.SEND2READ = will add the post-processed file to the readinglits
weeklypull.weekly_check(comicid, issuenum, file=(nfilename +ext), path=dst, module=module, issueid=issueid)
# retrieve/create the corresponding comic objects
if mylar.CONFIG.ENABLE_EXTRA_SCRIPTS:
folderp = dst #folder location after move/rename
nzbn = self.nzb_name #original nzb name
filen = nfilename + ext #new filename
#name, comicyear, comicid , issueid, issueyear, issue, publisher
#create the dic and send it.
seriesmeta = []
seriesmetadata = {}
seriesmeta.append({
'name': series,
'comicyear': seriesyear,
'comicid': comicid,
'issueid': issueid,
'issueyear': issueyear,
'issue': issuenum,
'publisher': publisher
})
seriesmetadata['seriesmeta'] = seriesmeta
self._run_extra_scripts(nzbn, self.nzb_folder, filen, folderp, seriesmetadata)
#if ml is not None:
# #we only need to return self.log if it's a manual run and it's not a snatched torrent
# #manual run + not snatched torrent (or normal manual-run)
# logger.info(module + ' Post-Processing completed for: ' + series + ' ' + dispiss)
# self._log(u"Post Processing SUCCESSFUL! ")
# self.valreturn.append({"self.log": self.log,
# "mode": 'stop',
# "issueid": issueid,
# "comicid": comicid})
# #if self.apicall is True:
# self.sendnotify(series, issueyear, dispiss, annchk, module)
# return self.queue.put(self.valreturn)
imageUrl = myDB.select('SELECT ImageURL from issues WHERE IssueID=?', [issueid])
if imageUrl:
imageUrl = imageUrl[0][0]
self.sendnotify(series, issueyear, dispiss, annchk, module, imageUrl)
logger.info('%s Post-Processing completed for: %s %s' % (module, series, dispiss))
self._log(u"Post Processing SUCCESSFUL! ")
self.valreturn.append({"self.log": self.log,
"mode": 'stop',
"issueid": issueid,
"comicid": comicid})
return self.queue.put(self.valreturn)
def sendnotify(self, series, issueyear, issuenumOG, annchk, module, imageUrl):
if issueyear is None:
prline = '%s %s' % (series, issuenumOG)
else:
prline = '%s (%s) %s' % (series, issueyear, issuenumOG)
prline2 = 'Mylar has downloaded and post-processed: ' + prline
if mylar.CONFIG.PROWL_ENABLED:
pushmessage = prline
prowl = notifiers.PROWL()
prowl.notify(pushmessage, "Download and Postprocessing completed", module=module)
if mylar.CONFIG.PUSHOVER_ENABLED:
pushover = notifiers.PUSHOVER()
pushover.notify(prline, prline2, module=module)
if mylar.CONFIG.BOXCAR_ENABLED:
boxcar = notifiers.BOXCAR()
boxcar.notify(prline=prline, prline2=prline2, module=module)
if mylar.CONFIG.PUSHBULLET_ENABLED:
pushbullet = notifiers.PUSHBULLET()
pushbullet.notify(prline=prline, prline2=prline2, module=module)
if mylar.CONFIG.TELEGRAM_ENABLED:
telegram = notifiers.TELEGRAM()
telegram.notify(prline2, imageUrl)
if mylar.CONFIG.SLACK_ENABLED:
slack = notifiers.SLACK()
slack.notify("Download and Postprocessing completed", prline2, module=module)
if mylar.CONFIG.EMAIL_ENABLED and mylar.CONFIG.EMAIL_ONPOST:
logger.info(u"Sending email notification")
email = notifiers.EMAIL()
email.notify(prline2, "Mylar notification - Processed", module=module)
return
class FolderCheck():
def __init__(self):
import Queue
import PostProcessor, logger
self.module = '[FOLDER-CHECK]'
self.queue = Queue.Queue()
def run(self):
if mylar.IMPORTLOCK:
logger.info('There is an import currently running. In order to ensure successful import - deferring this until the import is finished.')
return
#monitor a selected folder for 'snatched' files that haven't been processed
#junk the queue as it's not needed for folder monitoring, but needed for post-processing to run without error.
helpers.job_management(write=True, job='Folder Monitor', current_run=helpers.utctimestamp(), status='Running')
mylar.MONITOR_STATUS = 'Running'
logger.info('%s Checking folder %s for newly snatched downloads' % (self.module, mylar.CONFIG.CHECK_FOLDER))
PostProcess = PostProcessor('Manual Run', mylar.CONFIG.CHECK_FOLDER, queue=self.queue)
result = PostProcess.Process()
logger.info('%s Finished checking for newly snatched downloads' % self.module)
helpers.job_management(write=True, job='Folder Monitor', last_run_completed=helpers.utctimestamp(), status='Waiting')
mylar.MONITOR_STATUS = 'Waiting'
| 195,670 | Python | .py | 2,579 | 47.638232 | 399 | 0.463439 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,270 | locg.py | evilhero_mylar/mylar/locg.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
import requests
from bs4 import BeautifulSoup, UnicodeDammit
import datetime
import re
import mylar
from mylar import logger, db
def locg(pulldate=None,weeknumber=None,year=None):
todaydate = datetime.datetime.today().replace(second=0,microsecond=0)
if pulldate:
logger.info('pulldate is : ' + str(pulldate))
if pulldate is None or pulldate == '00000000':
weeknumber = todaydate.strftime("%U")
elif '-' in pulldate:
#find the week number
weektmp = datetime.date(*(int(s) for s in pulldate.split('-')))
weeknumber = weektmp.strftime("%U")
#we need to now make sure we default to the correct week
weeknumber_new = todaydate.strftime("%U")
if weeknumber_new > weeknumber:
weeknumber = weeknumber_new
else:
if str(weeknumber).isdigit() and int(weeknumber) <= 52:
#already requesting week #
weeknumber = weeknumber
else:
logger.warn('Invalid date requested. Aborting pull-list retrieval/update at this time.')
return {'status': 'failure'}
if year is None:
year = todaydate.strftime("%Y")
params = {'week': str(weeknumber),
'year': str(year)}
url = 'https://walksoftly.itsaninja.party/newcomics.php'
try:
r = requests.get(url, params=params, verify=True, headers={'User-Agent': mylar.USER_AGENT[:mylar.USER_AGENT.find('/')+7] + mylar.USER_AGENT[mylar.USER_AGENT.find('(')+1]})
except requests.exceptions.RequestException as e:
logger.warn(e)
return {'status': 'failure'}
if str(r.status_code) == '619':
logger.warn('[' + str(r.status_code) + '] No date supplied, or an invalid date was provided [' + str(pulldate) + ']')
return {'status': 'failure'}
elif str(r.status_code) == '999' or str(r.status_code) == '111':
logger.warn('[' + str(r.status_code) + '] Unable to retrieve data from site - this is a site.specific issue [' + str(pulldate) + ']')
return {'status': 'failure'}
elif str(r.status_code) == '200':
data = r.json()
logger.info('[WEEKLY-PULL] There are ' + str(len(data)) + ' issues for the week of ' + str(weeknumber) + ', ' + str(year))
pull = []
for x in data:
pull.append({'series': x['series'],
'alias': x['alias'],
'issue': x['issue'],
'publisher': x['publisher'],
'shipdate': x['shipdate'],
'coverdate': x['coverdate'],
'comicid': x['comicid'],
'issueid': x['issueid'],
'weeknumber': x['weeknumber'],
'annuallink': x['link'],
'year': x['year'],
'volume': x['volume'],
'seriesyear': x['seriesyear'],
'format': x['type']})
shipdate = x['shipdate']
myDB = db.DBConnection()
myDB.action("CREATE TABLE IF NOT EXISTS weekly (SHIPDATE, PUBLISHER text, ISSUE text, COMIC VARCHAR(150), EXTRA text, STATUS text, ComicID text, IssueID text, CV_Last_Update text, DynamicName text, weeknumber text, year text, volume text, seriesyear text, annuallink text, format text, rowid INTEGER PRIMARY KEY)")
#clear out the upcoming table here so they show the new values properly.
if pulldate == '00000000':
logger.info('Re-creating pullist to ensure everything\'s fresh.')
myDB.action('DELETE FROM weekly WHERE weeknumber=? AND year=?',[int(weeknumber), int(year)])
for x in pull:
comicid = None
issueid = None
comicname = x['series']
if x['comicid'] is not None:
comicid = x['comicid']
if x['issueid'] is not None:
issueid= x['issueid']
if x['alias'] is not None:
comicname = x['alias']
cl_d = mylar.filechecker.FileChecker()
cl_dyninfo = cl_d.dynamic_replace(comicname)
dynamic_name = re.sub('[\|\s]','', cl_dyninfo['mod_seriesname'].lower()).strip()
controlValueDict = {'DYNAMICNAME': dynamic_name,
'ISSUE': re.sub('#', '', x['issue']).strip()}
newValueDict = {'SHIPDATE': x['shipdate'],
'PUBLISHER': x['publisher'],
'STATUS': 'Skipped',
'COMIC': comicname,
'COMICID': comicid,
'ISSUEID': issueid,
'WEEKNUMBER': x['weeknumber'],
'ANNUALLINK': x['annuallink'],
'YEAR': x['year'],
'VOLUME': x['volume'],
'SERIESYEAR': x['seriesyear'],
'FORMAT': x['format']}
myDB.upsert("weekly", newValueDict, controlValueDict)
logger.info('[PULL-LIST] Successfully populated pull-list into Mylar for the week of: ' + str(weeknumber))
#set the last poll date/time here so that we don't start overwriting stuff too much...
mylar.CONFIG.PULL_REFRESH = todaydate
return {'status': 'success',
'count': len(data),
'weeknumber': weeknumber,
'year': year}
else:
if str(r.status_code) == '666':
logger.warn('[%s] The error returned is: %s' % (r.status_code, r.headers))
return {'status': 'update_required'}
else:
logger.warn('[%s] The error returned is: %s' % (r.status_code, r.headers))
return {'status': 'failure'}
| 7,016 | Python | .py | 125 | 40.144 | 326 | 0.517543 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,271 | parseit.py | evilhero_mylar/mylar/parseit.py | # This file is part of Mylar.
#
# Mylar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Mylar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Mylar. If not, see <http://www.gnu.org/licenses/>.
from bs4 import BeautifulSoup, UnicodeDammit
import urllib2
import re
import helpers
import logger
import datetime
import sys
from decimal import Decimal
from HTMLParser import HTMLParseError
from time import strptime
import mylar
def GCDScraper(ComicName, ComicYear, Total, ComicID, quickmatch=None):
NOWyr = datetime.date.today().year
if datetime.date.today().month == 12:
NOWyr = NOWyr + 1
logger.fdebug("We're in December, incremented search Year to increase search results: " + str(NOWyr))
comicnm = ComicName.encode('utf-8').strip()
comicyr = ComicYear
comicis = Total
comicid = ComicID
#print ( "comicname: " + str(comicnm) )
#print ( "comicyear: " + str(comicyr) )
#print ( "comichave: " + str(comicis) )
#print ( "comicid: " + str(comicid) )
comicnm_1 = re.sub('\+', '%2B', comicnm)
comicnm = re.sub(' ', '+', comicnm_1)
input = 'http://www.comics.org/search/advanced/process/?target=series&method=icontains&logic=False&order2=date&order3=&start_date=' + str(comicyr) + '-01-01&end_date=' + str(NOWyr) + '-12-31&series=' + str(comicnm) + '&is_indexed=None'
response = urllib2.urlopen (input)
soup = BeautifulSoup (response)
cnt1 = len(soup.findAll("tr", {"class": "listing_even"}))
cnt2 = len(soup.findAll("tr", {"class": "listing_odd"}))
cnt = int(cnt1 + cnt2)
#print (str(cnt) + " results")
resultName = []
resultID = []
resultYear = []
resultIssues = []
resultURL = None
n_odd = -1
n_even = -1
n = 0
while (n < cnt):
if n%2==0:
n_even+=1
resultp = soup.findAll("tr", {"class": "listing_even"})[n_even]
else:
n_odd+=1
resultp = soup.findAll("tr", {"class": "listing_odd"})[n_odd]
rtp = resultp('a')[1]
resultName.append(helpers.cleanName(rtp.findNext(text=True)))
#print ( "Comic Name: " + str(resultName[n]) )
fip = resultp('a', href=True)[1]
resultID.append(fip['href'])
#print ( "ID: " + str(resultID[n]) )
subtxt3 = resultp('td')[3]
resultYear.append(subtxt3.findNext(text=True))
resultYear[n] = resultYear[n].replace(' ', '')
subtxt4 = resultp('td')[4]
resultIssues.append(helpers.cleanName(subtxt4.findNext(text=True)))
resiss = resultIssues[n].find('issue')
resiss = int(resiss)
resultIssues[n] = resultIssues[n].replace('', '')[:resiss]
resultIssues[n] = resultIssues[n].replace(' ', '')
#print ( "Year: " + str(resultYear[n]) )
#print ( "Issues: " + str(resultIssues[n]) )
CleanComicName = re.sub('[\,\.\:\;\'\[\]\(\)\!\@\#\$\%\^\&\*\-\_\+\=\?\/]', '', comicnm)
CleanComicName = re.sub(' ', '', CleanComicName).lower()
CleanResultName = re.sub('[\,\.\:\;\'\[\]\(\)\!\@\#\$\%\^\&\*\-\_\+\=\?\/]', '', resultName[n])
CleanResultName = re.sub(' ', '', CleanResultName).lower()
#print ("CleanComicName: " + str(CleanComicName))
#print ("CleanResultName: " + str(CleanResultName))
if CleanResultName == CleanComicName or CleanResultName[3:] == CleanComicName:
#if resultName[n].lower() == helpers.cleanName(str(ComicName)).lower():
#print ("n:" + str(n) + "...matched by name to Mylar!")
#this has been seen in a few instances already, so trying to adjust.
#when the series year is 2011, in gcd it might be 2012 due to publication
#dates overlapping between Dec/11 and Jan/12. Let's accept a match with a
#1 year grace space, and then pull in the first issue to see the actual pub
# date and if coincides with the other date..match it.
if resultYear[n] == ComicYear or resultYear[n] == str(int(ComicYear) +1):
#print ("n:" + str(n) + "...matched by year to Mylar!")
#print ( "Year: " + str(resultYear[n]) )
#Occasionally there are discrepancies in comic count between
#GCD and CV. 99% it's CV not updating to the newest issue as fast
#as GCD does. Therefore, let's increase the CV count by 1 to get it
#to match, any more variation could cause incorrect matching.
#ie. witchblade on GCD says 159 issues, CV states 161.
if int(resultIssues[n]) == int(Total) or int(resultIssues[n]) == int(Total) +1 or (int(resultIssues[n]) +1) == int(Total):
#print ("initial issue match..continuing.")
if int(resultIssues[n]) == int(Total) +1:
issvariation = "cv"
elif int(resultIssues[n]) +1 == int(Total):
issvariation = "gcd"
else:
issvariation = "no"
#print ("n:" + str(n) + "...matched by issues to Mylar!")
#print ("complete match!...proceeding")
TotalIssues = resultIssues[n]
resultURL = str(resultID[n])
rptxt = resultp('td')[6]
resultPublished = rptxt.findNext(text=True)
#print ("Series Published: " + str(resultPublished))
break
n+=1
# it's possible that comicvine would return a comic name incorrectly, or gcd
# has the wrong title and won't match 100%...
# (ie. The Flash-2011 on comicvine is Flash-2011 on gcd)
# this section is to account for variations in spelling, punctuation, etc/
basnumbs = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12}
if resultURL is None:
#search for number as text, and change to numeric
for numbs in basnumbs:
#print ("numbs:" + str(numbs))
if numbs in ComicName.lower():
numconv = basnumbs[numbs]
#print ("numconv: " + str(numconv))
ComicNm = re.sub(str(numbs), str(numconv), ComicName.lower())
#print ("comicname-reVISED:" + str(ComicNm))
return GCDScraper(ComicNm, ComicYear, Total, ComicID)
break
if ComicName.lower().startswith('the '):
ComicName = ComicName[4:]
return GCDScraper(ComicName, ComicYear, Total, ComicID)
if ':' in ComicName:
ComicName = re.sub(':', '', ComicName)
return GCDScraper(ComicName, ComicYear, Total, ComicID)
if '-' in ComicName:
ComicName = re.sub('-', ' ', ComicName)
return GCDScraper(ComicName, ComicYear, Total, ComicID)
if 'and' in ComicName.lower():
ComicName = ComicName.replace('and', '&')
return GCDScraper(ComicName, ComicYear, Total, ComicID)
if not quickmatch: return 'No Match'
#vari_loop = 0
if quickmatch == "yes":
if resultURL is None: return 'No Match'
else: return 'Match'
return GCDdetails(comseries=None, resultURL=resultURL, vari_loop=0, ComicID=ComicID, TotalIssues=TotalIssues, issvariation=issvariation, resultPublished=resultPublished)
def GCDdetails(comseries, resultURL, vari_loop, ComicID, TotalIssues, issvariation, resultPublished):
gcdinfo = {}
gcdchoice = []
gcount = 0
i = 0
# datemonth = {'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'ten':10,'eleven':$
# #search for number as text, and change to numeric
# for numbs in basnumbs:
# #print ("numbs:" + str(numbs))
# if numbs in ComicName.lower():
# numconv = basnumbs[numbs]
# #print ("numconv: " + str(numconv))
if vari_loop > 1:
resultPublished = "Unknown"
if vari_loop == 99: vari_loop = 1
while (i <= vari_loop):
if vari_loop > 0:
try:
boong = comseries['comseries'][i]
except IndexError:
break
resultURL = boong['comseriesID']
ComicID = boong['comicid']
TotalIssues+= int(boong['comseriesIssues'])
else:
resultURL = resultURL
# if we're here - it means it's a mismatched name.
# let's pull down the publication date as it'll be blank otherwise
inputMIS = 'http://www.comics.org' + str(resultURL)
resp = urllib2.urlopen (inputMIS)
# soup = BeautifulSoup ( resp )
try:
soup = BeautifulSoup(urllib2.urlopen(inputMIS))
except UnicodeDecodeError:
logger.info("I've detected your system is using: " + sys.stdout.encoding)
logger.info("unable to parse properly due to utf-8 problem, ignoring wrong symbols")
try:
soup = BeautifulSoup(urllib2.urlopen(inputMIS)).decode('utf-8', 'ignore')
except UnicodeDecodeError:
logger.info("not working...aborting. Tell Evilhero.")
return
#If CV doesn't have the Series Year (Stupid)...Let's store the Comics.org stated year just in case.
pyearit = soup.find("div", {"class": "item_data"})
pyeartxt = pyearit.find(text=re.compile(r"Series"))
pyearst = pyeartxt.index('Series')
ParseYear = pyeartxt[int(pyearst) -5:int(pyearst)]
parsed = soup.find("div", {"id": "series_data"})
#recent structure changes - need to adjust now
subtxt3 = parsed.find("dd", {"id": "publication_dates"})
resultPublished = subtxt3.findNext(text=True).rstrip()
#print ("pubdate:" + str(resultPublished))
parsfind = parsed.findAll("dt", {"class": "long"})
seriesloop = len(parsfind)
resultFormat = ''
for pf in parsfind:
if 'Publishing Format:' in pf.findNext(text=True):
subtxt9 = pf.find("dd", {"id": "series_format"})
resultFormat = subtxt9.findNext(text=True).rstrip()
continue
# the caveat - if a series is ongoing but only has 1 issue published at a particular point in time,
# resultPublished will return just the date and not the word 'Present' which dictates on the main
# page if a series is Continuing / Ended .
if resultFormat != '':
if 'ongoing series' in resultFormat.lower() and 'was' not in resultFormat.lower() and 'present' not in resultPublished.lower():
resultPublished = resultPublished + " - Present"
if 'limited series' in resultFormat.lower() and '?' in resultPublished:
resultPublished = resultPublished + " (Limited Series)"
coverst = soup.find("div", {"id": "series_cover"})
if coverst < 0:
gcdcover = "None"
else:
subcoverst = coverst('img', src=True)[0]
gcdcover = subcoverst['src']
#print ("resultURL:" + str(resultURL))
#print ("comicID:" + str(ComicID))
input2 = 'http://www.comics.org' + str(resultURL) + 'details/'
resp = urllib2.urlopen(input2)
soup = BeautifulSoup(resp)
#for newer comics, on-sale date has complete date...
#for older comics, pub.date is to be used
# type = soup.find(text=' On-sale date ')
type = soup.find(text=' Pub. Date ')
if type:
#print ("on-sale date detected....adjusting")
datetype = "pub"
else:
#print ("pub date defaulting")
datetype = "on-sale"
cnt1 = len(soup.findAll("tr", {"class": "row_even_False"}))
cnt2 = len(soup.findAll("tr", {"class": "row_even_True"}))
cnt = int(cnt1 + cnt2)
#print (str(cnt) + " Issues in Total (this may be wrong due to alternate prints, etc")
n_odd = -1
n_even = -1
n = 0
PI = "1.00"
altcount = 0
PrevYRMO = "0000-00"
while (n < cnt):
if n%2==0:
n_odd+=1
parsed = soup.findAll("tr", {"class": "row_even_False"})[n_odd]
ntype = "odd"
else:
n_even+=1
ntype = "even"
parsed = soup.findAll("tr", {"class": "row_even_True"})[n_even]
subtxt3 = parsed.find("a")
ParseIssue = subtxt3.findNext(text=True)
fid = parsed('a', href=True)[0]
resultGID = fid['href']
resultID = resultGID[7:-1]
if ',' in ParseIssue: ParseIssue = re.sub("\,", "", ParseIssue)
variant="no"
if 'Vol' in ParseIssue or '[' in ParseIssue or 'a' in ParseIssue or 'b' in ParseIssue or 'c' in ParseIssue:
m = re.findall('[^\[\]]+', ParseIssue)
# ^^ takes care of []
# if it's a decimal - variant ...whoo-boy is messed.
if '.' in m[0]:
dec_chk = m[0]
#if it's a digit before and after decimal, assume decimal issue
dec_st = dec_chk.find('.')
dec_b4 = dec_chk[:dec_st]
dec_ad = dec_chk[dec_st +1:]
dec_ad = re.sub("\s", "", dec_ad)
if dec_b4.isdigit() and dec_ad.isdigit():
#logger.fdebug("Alternate decimal issue...*Whew* glad I caught that")
ParseIssue = dec_b4 + "." + dec_ad
else:
#logger.fdebug("it's a decimal, but there's no digits before or after decimal")
#not a decimal issue, drop it down to the regex below.
ParseIssue = re.sub("[^0-9]", " ", dec_chk)
else:
ParseIssue = re.sub("[^0-9]", " ", m[0])
# ^^ removes everything but the digits from the remaining non-brackets
logger.fdebug("variant cover detected : " + str(ParseIssue))
variant="yes"
altcount = 1
isslen = ParseIssue.find(' ')
if isslen < 0:
#logger.fdebug("just digits left..using " + str(ParseIssue))
isslen == 0
isschk = ParseIssue
#logger.fdebug("setting ParseIssue to isschk: " + str(isschk))
else:
#logger.fdebug("parse issue is " + str(ParseIssue))
#logger.fdebug("more than digits left - first space detected at position : " + str(isslen))
#if 'isslen' exists, it means that it's an alternative cover.
#however, if ONLY alternate covers exist of an issue it won't work.
#let's use the FIRST record, and ignore all other covers for the given issue.
isschk = ParseIssue[:isslen]
#logger.fdebug("Parsed Issue#: " + str(isschk))
ParseIssue = re.sub("\s", "", ParseIssue)
#check if decimal or '1/2' exists or not, and store decimal results
halfchk = "no"
if '.' in isschk:
isschk_find = isschk.find('.')
isschk_b4dec = isschk[:isschk_find]
isschk_decval = isschk[isschk_find +1:]
#logger.fdebug("decimal detected for " + str(isschk))
#logger.fdebug("isschk_decval is " + str(isschk_decval))
if len(isschk_decval) == 1:
ParseIssue = isschk_b4dec + "." + str(int(isschk_decval) * 10)
elif '/' in isschk:
ParseIssue = "0.50"
isslen = 0
halfchk = "yes"
else:
isschk_decval = ".00"
ParseIssue = ParseIssue + isschk_decval
if variant == "yes":
#logger.fdebug("alternate cover detected - skipping/ignoring.")
altcount = 1
# in order to get the compare right, let's decimialize the string to '.00'.
# if halfchk == "yes": pass
# else:
# ParseIssue = ParseIssue + isschk_decval
datematch="false"
if not any(d.get('GCDIssue', None) == str(ParseIssue) for d in gcdchoice):
#logger.fdebug("preparing to add issue to db : " + str(ParseIssue))
pass
else:
#logger.fdebug("2 identical issue #'s have been found...determining if it's intentional")
#get current issue & publication date.
#logger.fdebug("Issue #:" + str(ParseIssue))
#logger.fdebug("IssueDate: " + str(gcdinfo['ComicDate']))
#get conflicting issue from tuple
for d in gcdchoice:
if str(d['GCDIssue']) == str(ParseIssue):
#logger.fdebug("Issue # already in tuple - checking IssueDate:" + str(d['GCDDate']) )
if str(d['GCDDate']) == str(gcdinfo['ComicDate']):
#logger.fdebug("Issue #'s and dates match...skipping.")
datematch="true"
else:
#logger.fdebug("Issue#'s match but different publication dates, not skipping.")
datematch="false"
if datematch == "false":
gcdinfo['ComicIssue'] = ParseIssue
#--- let's use pubdate.
#try publicationd date first
ParseDate = GettheDate(parsed, PrevYRMO)
ParseDate = ParseDate.replace(' ', '')
PrevYRMO = ParseDate
gcdinfo['ComicDate'] = ParseDate
#^^ will retrieve date #
#logger.fdebug("adding: " + str(gcdinfo['ComicIssue']) + " - date: " + str(ParseDate))
if ComicID[:1] == "G":
gcdchoice.append({
'GCDid': ComicID,
'IssueID': resultID,
'GCDIssue': gcdinfo['ComicIssue'],
'GCDDate': gcdinfo['ComicDate']
})
gcount+=1
else:
gcdchoice.append({
'GCDid': ComicID,
'GCDIssue': gcdinfo['ComicIssue'],
'GCDDate': gcdinfo['ComicDate']
})
gcdinfo['gcdchoice'] = gcdchoice
altcount = 0
n+=1
i+=1
gcdinfo['gcdvariation'] = issvariation
if ComicID[:1] == "G":
gcdinfo['totalissues'] = gcount
else:
gcdinfo['totalissues'] = TotalIssues
gcdinfo['ComicImage'] = gcdcover
gcdinfo['resultPublished'] = resultPublished
gcdinfo['SeriesYear'] = ParseYear
gcdinfo['GCDComicID'] = resultURL.split('/')[0]
return gcdinfo
## -- end (GCD) -- ##
def GettheDate(parsed, PrevYRMO):
#--- let's use pubdate.
#try publicationd date first
#logger.fdebug("parsed:" + str(parsed))
subtxt1 = parsed('td')[1]
ParseDate = subtxt1.findNext(text=True).rstrip()
pformat = 'pub'
if ParseDate is None or ParseDate == '':
subtxt1 = parsed('td')[2]
ParseDate = subtxt1.findNext(text=True)
pformat = 'on-sale'
if len(ParseDate) < 7: ParseDate = '0000-00' #invalid on-sale date format , drop it 0000-00 to avoid errors
basmonths = {'january': '01', 'february': '02', 'march': '03', 'april': '04', 'may': '05', 'june': '06', 'july': '07', 'august': '08', 'september': '09', 'october': '10', 'november': '11', 'december': '12'}
pdlen = len(ParseDate)
pdfind = ParseDate.find(' ', 2)
#logger.fdebug("length: " + str(pdlen) + "....first space @ pos " + str(pdfind))
#logger.fdebug("this should be the year: " + str(ParseDate[pdfind+1:pdlen-1]))
if pformat == 'on-sale': pass # date is in correct format...
else:
if ParseDate[pdfind +1:pdlen -1].isdigit():
#assume valid date.
#search for number as text, and change to numeric
for numbs in basmonths:
if numbs in ParseDate.lower():
pconv = basmonths[numbs]
ParseYear = re.sub('/s', '', ParseDate[-5:])
ParseDate = str(ParseYear) + "-" + str(pconv)
#logger.fdebug("!success - Publication date: " + str(ParseDate))
break
# some comics are messed with pub.dates and have Spring/Summer/Fall/Winter
else:
baseseasons = {'spring': '03', 'summer': '06', 'fall': '09', 'winter': '12'}
for seas in baseseasons:
if seas in ParseDate.lower():
sconv = baseseasons[seas]
ParseYear = re.sub('/s', '', ParseDate[-5:])
ParseDate = str(ParseYear) + "-" + str(sconv)
break
# #try key date
# subtxt1 = parsed('td')[2]
# ParseDate = subtxt1.findNext(text=True)
# #logger.fdebug("no pub.date detected, attempting to use on-sale date: " + str(ParseDate))
# if (ParseDate) < 7:
# #logger.fdebug("Invalid on-sale date - less than 7 characters. Trying Key date")
# subtxt3 = parsed('td')[0]
# ParseDate = subtxt3.findNext(text=True)
# if ParseDate == ' ':
#increment previous month by one and throw it in until it's populated properly.
if PrevYRMO == '0000-00':
ParseDate = '0000-00'
else:
PrevYR = str(PrevYRMO)[:4]
PrevMO = str(PrevYRMO)[5:]
#let's increment the month now (if it's 12th month, up the year and hit Jan.)
if int(PrevMO) == 12:
PrevYR = int(PrevYR) + 1
PrevMO = 1
else:
PrevMO = int(PrevMO) + 1
if int(PrevMO) < 10:
PrevMO = "0" + str(PrevMO)
ParseDate = str(PrevYR) + "-" + str(PrevMO)
#logger.fdebug("parseDAte:" + str(ParseDate))
return ParseDate
def GCDAdd(gcdcomicid):
serieschoice = []
series = {}
logger.fdebug("I'm trying to find these GCD comicid's:" + str(gcdcomicid))
for gcdid in gcdcomicid:
logger.fdebug("looking at gcdid:" + str(gcdid))
input2 = 'http://www.comics.org/series/' + str(gcdid)
logger.fdebug("---url: " + str(input2))
resp = urllib2.urlopen (input2)
soup = BeautifulSoup (resp)
logger.fdebug("SeriesName section...")
parsen = soup.find("span", {"id": "series_name"})
#logger.fdebug("series name (UNPARSED): " + str(parsen))
subpar = parsen('a')[0]
resultName = subpar.findNext(text=True)
logger.fdebug("ComicName: " + str(resultName))
#covers-start
logger.fdebug("Covers section...")
coverst = soup.find("div", {"id": "series_cover"})
if coverst < 0:
gcdcover = "None"
logger.fdebug("unable to find any covers - setting to None")
else:
subcoverst = coverst('img', src=True)[0]
#logger.fdebug("cover (UNPARSED) : " + str(subcoverst))
gcdcover = subcoverst['src']
logger.fdebug("Cover: " + str(gcdcover))
#covers end
#publisher start
logger.fdebug("Publisher section...")
try:
pubst = soup.find("div", {"class": "item_data"})
catchit = pubst('a')[0]
except (IndexError, TypeError):
pubst = soup.findAll("div", {"class": "left"})[1]
catchit = pubst.find("a")
publisher = catchit.findNext(text=True)
logger.fdebug("Publisher: " + str(publisher))
#publisher end
parsed = soup.find("div", {"id": "series_data"})
#logger.fdebug("series_data: " + str(parsed))
#print ("parse:" + str(parsed))
subtxt3 = parsed.find("dd", {"id": "publication_dates"})
#logger.fdebug("publication_dates: " + str(subtxt3))
pubdate = subtxt3.findNext(text=True).rstrip()
logger.fdebug("pubdate:" + str(pubdate))
subtxt4 = parsed.find("dd", {"id": "issues_published"})
noiss = subtxt4.findNext(text=True)
lenwho = len(noiss)
lent = noiss.find(' ', 2)
lenf = noiss.find('(')
stringit = noiss[lenf:lenwho]
stringout = noiss[:lent]
noissues = stringout.rstrip(' \t\r\n\0')
numbering = stringit.rstrip(' \t\r\n\0')
logger.fdebug("noissues:" + str(noissues))
logger.fdebug("numbering:" + str(numbering))
serieschoice.append({
"ComicID": gcdid,
"ComicName": resultName,
"ComicYear": pubdate,
"ComicIssues": noissues,
"ComicPublisher": publisher,
"ComicCover": gcdcover
})
series['serieschoice'] = serieschoice
return series
def ComChk(ComicName, ComicYear, ComicPublisher, Total, ComicID):
comchkchoice = []
comchoice = {}
NOWyr = datetime.date.today().year
if datetime.date.today().month == 12:
NOWyr = NOWyr + 1
logger.fdebug("We're in December, incremented search Year to increase search results: " + str(NOWyr))
comicnm = ComicName.encode('utf-8').strip()
comicyr = ComicYear
comicis = Total
comicid = ComicID
comicpub = ComicPublisher.encode('utf-8').strip()
#print ("...comchk parser initialization...")
#print ( "comicname: " + str(comicnm) )
#print ( "comicyear: " + str(comicyr) )
#print ( "comichave: " + str(comicis) )
#print ( "comicpub: " + str(comicpub) )
#print ( "comicid: " + str(comicid) )
# do 3 runs at the comics.org search to get the best results
comicrun = []
# &pub_name=DC
# have to remove the spaces from Publisher or else will not work (ie. DC Comics vs DC will not match)
# take the 1st word ;)
#comicpub = comicpub.split()[0]
# if it's not one of the BIG publisher's it might fail - so let's increase the odds.
pubbiggies = ['DC',
'Marvel',
'Image',
'IDW']
uhuh = "no"
for pb in pubbiggies:
if pb in comicpub:
#keep publisher in url if a biggie.
uhuh = "yes"
#print (" publisher match : " + str(comicpub))
conv_pub = comicpub.split()[0]
#print (" converted publisher to : " + str(conv_pub))
#1st run setup - leave it all as it is.
comicrun.append(comicnm)
cruncnt = 0
#2nd run setup - remove the last character and do a broad search (keep year or else will blow up)
if len(str(comicnm).split()) > 2:
comicrun.append(' '.join(comicnm.split(' ')[:-1]))
cruncnt+=1
# to increase the likely hood of matches and to get a broader scope...
# lets remove extra characters
if re.sub('[\.\,\:]', '', comicnm) != comicnm:
comicrun.append(re.sub('[\.\,\:]', '', comicnm))
cruncnt+=1
# one more addition - if the title contains a 'the', remove it ;)
if comicnm.lower().startswith('the'):
comicrun.append(comicnm[4:].strip())
cruncnt+=1
totalcount = 0
cr = 0
#print ("cruncnt is " + str(cruncnt))
while (cr <= cruncnt):
#print ("cr is " + str(cr))
comicnm = comicrun[cr]
#leaving spaces in will screw up the search...let's take care of it
comicnm = re.sub(' ', '+', comicnm)
#print ("comicnm: " + str(comicnm))
if uhuh == "yes":
publink = "&pub_name=" + str(conv_pub)
if uhuh == "no":
publink = "&pub_name="
input = 'http://www.comics.org/search/advanced/process/?target=series&method=icontains&logic=False&keywords=&order1=series&order2=date&order3=&start_date=' + str(comicyr) + '-01-01&end_date=' + str(NOWyr) + '-12-31' + '&title=&feature=&job_number=&pages=&script=&pencils=&inks=&colors=&letters=&story_editing=&genre=&characters=&synopsis=&reprint_notes=&story_reprinted=None¬es=' + str(publink) + '&pub_notes=&brand=&brand_notes=&indicia_publisher=&is_surrogate=None&ind_pub_notes=&series=' + str(comicnm) + '&series_year_began=&series_notes=&tracking_notes=&issue_count=&is_comics=None&format=&color=&dimensions=&paper_stock=&binding=&publishing_format=&issues=&volume=&issue_title=&variant_name=&issue_date=&indicia_frequency=&price=&issue_pages=&issue_editing=&isbn=&barcode=&issue_notes=&issue_reprinted=None&is_indexed=None'
response = urllib2.urlopen (input)
soup = BeautifulSoup (response)
cnt1 = len(soup.findAll("tr", {"class": "listing_even"}))
cnt2 = len(soup.findAll("tr", {"class": "listing_odd"}))
cnt = int(cnt1 + cnt2)
# print ("cnt1: " + str(cnt1))
# print ("cnt2: " + str(cnt2))
# print (str(cnt) + " results")
resultName = []
resultID = []
resultYear = []
resultIssues = []
resultPublisher = []
resultURL = None
n_odd = -1
n_even = -1
n = 0
while (n < cnt):
if n%2==0:
n_even+=1
resultp = soup.findAll("tr", {"class": "listing_even"})[n_even]
else:
n_odd+=1
resultp = soup.findAll("tr", {"class": "listing_odd"})[n_odd]
rtp = resultp('a')[1]
rtpit = rtp.findNext(text=True)
rtpthis = rtpit.encode('utf-8').strip()
resultName.append(helpers.cleanName(rtpthis))
# print ( "Comic Name: " + str(resultName[n]) )
pub = resultp('a')[0]
pubit = pub.findNext(text=True)
# pubthis = u' '.join(pubit).encode('utf-8').strip()
pubthis = pubit.encode('utf-8').strip()
resultPublisher.append(pubthis)
# print ( "Publisher: " + str(resultPublisher[n]) )
fip = resultp('a', href=True)[1]
resultID.append(fip['href'])
# print ( "ID: " + str(resultID[n]) )
subtxt3 = resultp('td')[3]
resultYear.append(subtxt3.findNext(text=True))
resultYear[n] = resultYear[n].replace(' ', '')
subtxt4 = resultp('td')[4]
resultIssues.append(helpers.cleanName(subtxt4.findNext(text=True)))
resiss = resultIssues[n].find('issue')
resiss = int(resiss)
resultIssues[n] = resultIssues[n].replace('', '')[:resiss]
resultIssues[n] = resultIssues[n].replace(' ', '')
# print ( "Year: " + str(resultYear[n]) )
# print ( "Issues: " + str(resultIssues[n]) )
# print ("comchkchoice: " + str(comchkchoice))
if not any(d.get('GCDID', None) == str(resultID[n]) for d in comchkchoice):
#print ( str(resultID[n]) + " not in DB...adding.")
comchkchoice.append({
"ComicID": str(comicid),
"ComicName": resultName[n],
"GCDID": str(resultID[n]).split('/')[2],
"ComicYear": str(resultYear[n]),
"ComicPublisher": resultPublisher[n],
"ComicURL": "http://www.comics.org" + str(resultID[n]),
"ComicIssues": str(resultIssues[n])
})
#else:
#print ( str(resultID[n]) + " already in DB...skipping" )
n+=1
cr+=1
totalcount= totalcount + cnt
comchoice['comchkchoice'] = comchkchoice
return comchoice, totalcount
def decode_html(html_string):
converted = UnicodeDammit(html_string)
if not converted.unicode:
raise UnicodeDecodeError(
"Failed to detect encoding, tried [%s]",
', '.join(converted.triedEncodings))
# print converted.originalEncoding
return converted.unicode
def annualCheck(gcomicid, comicid, comicname, comicyear):
# will only work if we already matched for gcd.
# search for <comicname> annual
# grab annual listing that hits on comicyear (seriesyear)
# grab results :)
print ("GcomicID: " + str(gcomicid))
print ("comicID: " + str(comicid))
print ("comicname: " + comicname)
print ("comicyear: " + str(comicyear))
comicnm = comicname.encode('utf-8').strip()
comicnm_1 = re.sub('\+', '%2B', comicnm + " annual")
comicnm = re.sub(' ', '+', comicnm_1)
input = 'http://www.comics.org/search/advanced/process/?target=series&method=icontains&logic=False&order2=date&order3=&start_date=' + str(comicyear) + '-01-01&end_date=' + str(comicyear) + '-12-31&series=' + str(comicnm) + '&is_indexed=None'
response = urllib2.urlopen (input)
soup = BeautifulSoup (response)
cnt1 = len(soup.findAll("tr", {"class": "listing_even"}))
cnt2 = len(soup.findAll("tr", {"class": "listing_odd"}))
cnt = int(cnt1 + cnt2)
print (str(cnt) + " results")
resultName = []
resultID = []
resultYear = []
resultIssues = []
resultURL = None
n_odd = -1
n_even = -1
n = 0
while (n < cnt):
if n%2==0:
n_even+=1
resultp = soup.findAll("tr", {"class": "listing_even"})[n_even]
else:
n_odd+=1
resultp = soup.findAll("tr", {"class": "listing_odd"})[n_odd]
rtp = resultp('a')[1]
rtp1 = re.sub('Annual', '', rtp)
resultName.append(helpers.cleanName(rtp1.findNext(text=True)))
print ("Comic Name: " + str(resultName[n]))
fip = resultp('a', href=True)[1]
resultID.append(fip['href'])
print ("ID: " + str(resultID[n]))
subtxt3 = resultp('td')[3]
resultYear.append(subtxt3.findNext(text=True))
resultYear[n] = resultYear[n].replace(' ', '')
subtxt4 = resultp('td')[4]
resultIssues.append(helpers.cleanName(subtxt4.findNext(text=True)))
resiss = resultIssues[n].find('issue')
resiss = int(resiss)
resultIssues[n] = resultIssues[n].replace('', '')[:resiss]
resultIssues[n] = resultIssues[n].replace(' ', '')
print ("Year: " + str(resultYear[n]))
print ("Issues: " + str(resultIssues[n]))
CleanComicName = re.sub('[\,\.\:\;\'\[\]\(\)\!\@\#\$\%\^\&\*\-\_\+\=\?\/]', '', comicnm)
CleanComicName = re.sub(' ', '', CleanComicName).lower()
CleanResultName = re.sub('[\,\.\:\;\'\[\]\(\)\!\@\#\$\%\^\&\*\-\_\+\=\?\/]', '', resultName[n])
CleanResultName = re.sub(' ', '', CleanResultName).lower()
print ("CleanComicName: " + str(CleanComicName))
print ("CleanResultName: " + str(CleanResultName))
if CleanResultName == CleanComicName or CleanResultName[3:] == CleanComicName:
#if resultName[n].lower() == helpers.cleanName(str(ComicName)).lower():
#print ("n:" + str(n) + "...matched by name to Mylar!")
if resultYear[n] == ComicYear or resultYear[n] == str(int(ComicYear) +1):
print ("n:" + str(n) + "...matched by year to Mylar!")
print ("Year: " + str(resultYear[n]))
TotalIssues = resultIssues[n]
resultURL = str(resultID[n])
rptxt = resultp('td')[6]
resultPublished = rptxt.findNext(text=True)
#print ("Series Published: " + str(resultPublished))
break
n+=1
return
| 36,412 | Python | .py | 733 | 38.502046 | 840 | 0.550347 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,272 | rtorrent.py | evilhero_mylar/mylar/torrent/clients/rtorrent.py | import os
import re
from urlparse import urlparse
from lib.rtorrent import RTorrent
import mylar
from mylar import logger, helpers
class TorrentClient(object):
def __init__(self):
self.conn = None
def getVerifySsl(self, verify, ca_bundle):
# Ensure verification has been enabled
if not verify:
return False
# Use ca bundle if defined
if ca_bundle is not None and os.path.exists(ca_bundle):
return ca_bundle
# Use default ssl verification
return True
def connect(self, host, username, password, auth, verify, rpc_url, ca_bundle, test=False):
if self.conn is not None:
return self.conn
if not host:
return {'status': False, 'error': 'No host specified'}
url = host
if host.startswith('https:'):
ssl = True
else:
if not host.startswith('http://'):
url = 'http://' + url
ssl = False
#add on the slash ..
if not url.endswith('/'):
url += '/'
#url = helpers.cleanHost(host, protocol = True, ssl = ssl)
# Automatically add '+https' to 'httprpc' protocol if SSL is enabled
#if ssl is True and url.startswith('httprpc://'):
# url = url.replace('httprpc://', 'httprpc+https://')
#if ssl is False and not url.startswith('http://'):
# url = 'http://' + url
#parsed = urlparse(url)
# rpc_url is only used on http/https scgi pass-through
if rpc_url is not None:
url += rpc_url
#logger.fdebug(url)
if username and password:
try:
self.conn = RTorrent(
url,(auth, username, password),
verify_server=True,
verify_ssl=self.getVerifySsl(verify, ca_bundle)
)
except Exception as err:
logger.error('Make sure you have the right protocol specified for the rtorrent host. Failed to connect to rTorrent - error: %s.' % err)
return {'status': False, 'error': err}
else:
logger.fdebug('NO username %s / NO password %s' % (username, password))
try:
self.conn = RTorrent(
url, (auth, username, password),
verify_server=True,
verify_ssl=self.getVerifySsl(verify, ca_bundle)
)
except Exception as err:
logger.error('Failed to connect to rTorrent: %s' % err)
return {'status': False, 'error': err}
if test is True:
return {'status': True, 'version': self.conn.get_client_version()}
else:
return self.conn
def find_torrent(self, hash):
return self.conn.find_torrent(hash)
def get_torrent (self, torrent):
torrent_files = []
torrent_directory = os.path.normpath(torrent.directory)
try:
for f in torrent.get_files():
if not os.path.normpath(f.path).startswith(torrent_directory):
file_path = os.path.join(torrent_directory, f.path.lstrip('/'))
else:
file_path = f.path
torrent_files.append(file_path)
torrent_info = {
'hash': torrent.info_hash,
'name': torrent.name,
'label': torrent.get_custom1() if torrent.get_custom1() else '',
'folder': torrent_directory,
'completed': torrent.complete,
'files': torrent_files,
'upload_total': torrent.get_up_total(),
'download_total': torrent.get_down_total(),
'ratio': torrent.get_ratio(),
'total_filesize': torrent.get_size_bytes(),
'time_started': torrent.get_time_started()
}
except Exception:
raise
return torrent_info if torrent_info else False
def load_torrent(self, filepath):
start = bool(mylar.CONFIG.RTORRENT_STARTONLOAD)
if filepath.startswith('magnet'):
logger.fdebug('torrent magnet link set to : ' + filepath)
torrent_hash = re.findall('urn:btih:([\w]{32,40})', filepath)[0].upper()
# Send request to rTorrent
try:
#cannot verify_load magnet as it might take a very very long time for it to retrieve metadata
torrent = self.conn.load_magnet(filepath, torrent_hash, verify_load=True)
if not torrent:
logger.error('Unable to find the torrent, did it fail to load?')
return False
except Exception as err:
logger.error('Failed to send magnet to rTorrent: %s', err)
return False
else:
logger.info('Torrent successfully loaded into rtorrent using magnet link as source.')
else:
logger.fdebug('filepath to torrent file set to : ' + filepath)
try:
torrent = self.conn.load_torrent(filepath, verify_load=True)
if not torrent:
logger.error('Unable to find the torrent, did it fail to load?')
return False
except Exception as err:
logger.error('Failed to send torrent to rTorrent: %s', err)
return False
#we can cherrypick the torrents here if required and if it's a pack (0day instance)
#torrent.get_files() will return list of files in torrent
#f.set_priority(0,1,2)
#for f in torrent.get_files():
# logger.info('torrent_get_files: %s' % f)
# f.set_priority(0) #set them to not download just to see if this works...
#torrent.updated_priorities()
if mylar.CONFIG.RTORRENT_LABEL is not None:
torrent.set_custom(1, mylar.CONFIG.RTORRENT_LABEL)
logger.fdebug('Setting label for torrent to : ' + mylar.CONFIG.RTORRENT_LABEL)
if mylar.CONFIG.RTORRENT_DIRECTORY is not None:
torrent.set_directory(mylar.CONFIG.RTORRENT_DIRECTORY)
logger.fdebug('Setting directory for torrent to : ' + mylar.CONFIG.RTORRENT_DIRECTORY)
logger.info('Successfully loaded torrent.')
#note that if set_directory is enabled, the torrent has to be started AFTER it's loaded or else it will give chunk errors and not seed
if start:
logger.info('[' + str(start) + '] Now starting torrent.')
torrent.start()
else:
logger.info('[' + str(start) + '] Not starting torrent due to configuration setting.')
return True
def start_torrent(self, torrent):
return torrent.start()
def stop_torrent(self, torrent):
return torrent.stop()
def delete_torrent(self, torrent):
deleted = []
try:
for file_item in torrent.get_files():
file_path = os.path.join(torrent.directory, file_item.path)
os.unlink(file_path)
deleted.append(file_item.path)
if torrent.is_multi_file() and torrent.directory.endswith(torrent.name):
try:
for path, _, _ in os.walk(torrent.directory, topdown=False):
os.rmdir(path)
deleted.append(path)
except:
pass
except Exception:
raise
torrent.erase()
return deleted
| 7,595 | Python | .py | 167 | 32.886228 | 151 | 0.566153 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,273 | transmission.py | evilhero_mylar/mylar/torrent/clients/transmission.py | import os
import mylar
from mylar import logger
from transmissionrpc import Client
class TorrentClient(object):
def __init__(self):
self.conn = None
def connect(self, host, username, password):
if self.conn is not None:
return self.conn
if not host:
return False
try:
if username and password:
self.conn = Client(
host,
user=username,
password=password
)
else:
self.conn = Client(host)
except:
logger.error('Could not connect to %h' % host)
return False
return self.conn
def find_torrent(self, hash):
try:
return self.conn.get_torrent(hash)
except KeyError:
logger.error('torrent %s does not exist')
return False
def get_torrent(self, torrent):
torrent = self.conn.get_torrent(torrent.hashString)
torrent_files = []
torrent_directory = os.path.normpath(torrent.downloadDir)
for f in torrent.files().itervalues():
if not os.path.normpath(f['name']).startswith(torrent_directory):
file_path = os.path.join(torrent_directory,
f['name'].lstrip('/'))
else:
file_path = f['name']
torrent_files.append(file_path)
torrent_info = {
'hash': torrent.hashString,
'name': torrent.name,
'folder': torrent.downloadDir,
'completed': torrent.progress == 100,
'label': 'None', ## labels not supported in transmission - for when it's in transmission
'files': torrent_files,
'upload_total': torrent.uploadedEver,
'download_total': torrent.downloadedEver,
'ratio': torrent.ratio,
'total_filesize': torrent.sizeWhenDone,
'time_started': torrent.date_started
}
logger.debug(torrent_info)
return torrent_info if torrent_info else False
def start_torrent(self, torrent):
return torrent.start()
def stop_torrent(self, torrent):
return torrent.stop()
def load_torrent(self, filepath):
if any([mylar.CONFIG.TRANSMISSION_DIRECTORY is None, mylar.CONFIG.TRANSMISSION_DIRECTORY == '', mylar.CONFIG.TRANSMISSION_DIRECTORY == 'None']):
down_dir = mylar.CONFIG.CHECK_FOLDER
else:
down_dir = mylar.CONFIG.TRANSMISSION_DIRECTORY
if filepath.startswith('magnet'):
torrent = self.conn.add_torrent('%s' % filepath,
download_dir=down_dir)
else:
torrent = self.conn.add_torrent('file://%s' % filepath,
download_dir=down_dir)
torrent.start()
return self.get_torrent(torrent)
def delete_torrent(self, torrent):
deleted = []
files = torrent.files()
for file_item in files.itervalues():
file_path = os.path.join(torrent.downloadDir,
file_item['name'])
deleted.append(file_path)
if len(files) > 1:
torrent_path = os.path.join(torrent.downloadDir, torrent.name)
for path, _, _ in os.walk(torrent_path, topdown=False):
deleted.append(path)
if self.conn.remove_torrent(torrent.hashString, delete_data=True):
return deleted
else:
logger.error('Unable to delete %s' % torrent.name)
return []
| 3,660 | Python | .py | 90 | 28.344444 | 152 | 0.561497 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,274 | qbittorrent.py | evilhero_mylar/mylar/torrent/clients/qbittorrent.py | import os
import mylar
from base64 import b16encode, b32decode
import re
import time
from mylar import logger, helpers
from lib.qbittorrent import client
class TorrentClient(object):
def __init__(self):
self.conn = None
def connect(self, host, username, password, test=False):
if self.conn is not None:
return self.connect
if not host:
return {'status': False, 'error': 'host not specified'}
try:
self.client = client.Client(host)
except Exception as e:
logger.error('Could not create qBittorrent Object %s' % e)
return {'status': False, 'error': e}
else:
try:
self.client.login(username, password)
except Exception as e:
logger.error('Could not connect to qBittorrent: %s' % host)
return {'status': False, 'error': e}
else:
if test is True:
version = self.client.qbittorrent_version
return {'status': True, 'version': version}
else:
return self.client
def find_torrent(self, hash):
logger.debug('Finding Torrent hash: %s' % hash)
torrent_info = self.get_torrent(hash)
if torrent_info:
return True
else:
return False
def get_torrent(self, hash):
logger.debug('Getting Torrent info hash: %s' % hash)
try:
torrent_info = self.client.get_torrent(hash)
except Exception as e:
logger.error('Could not get torrent info for %s' % hash)
return False
else:
logger.info('Successfully located information for torrent')
return torrent_info
def load_torrent(self, filepath):
if not filepath.startswith('magnet'):
logger.info('filepath to torrent file set to : %s' % filepath)
if self.client._is_authenticated is True:
logger.info('Checking if Torrent Exists!')
if filepath.startswith('magnet'):
torrent_hash = re.findall("urn:btih:([\w]{32,40})", filepath)[0]
if len(torrent_hash) == 32:
torrent_hash = b16encode(b32decode(torrent_hash)).lower()
hash = torrent_hash.upper()
logger.debug('Magnet (load_torrent) initiating')
else:
hash = self.get_the_hash(filepath)
logger.debug('FileName (load_torrent): %s' % os.path.basename(filepath))
logger.debug('Torrent Hash (load_torrent): "%s"' % hash)
#Check if torrent already added
if self.find_torrent(hash):
logger.info('load_torrent: Torrent already exists!')
return {'status': False, 'error': 'Torrent already exists'}
#should set something here to denote that it's already loaded, and then the failed download checker not run so it doesn't download
#multiple copies of the same issues that's already downloaded
else:
logger.info('Torrent not added yet, trying to add it now!')
# Build an arg dict based on user prefs.
addargs = {}
if not any([mylar.CONFIG.QBITTORRENT_LABEL is None, mylar.CONFIG.QBITTORRENT_LABEL == '', mylar.CONFIG.QBITTORRENT_LABEL == 'None']):
addargs.update( { 'category': str(mylar.CONFIG.QBITTORRENT_LABEL) } )
logger.info('Setting download label to: %s' % mylar.CONFIG.QBITTORRENT_LABEL)
if not any([mylar.CONFIG.QBITTORRENT_FOLDER is None, mylar.CONFIG.QBITTORRENT_FOLDER == '', mylar.CONFIG.QBITTORRENT_FOLDER == 'None']):
addargs.update( { 'savepath': str(mylar.CONFIG.QBITTORRENT_FOLDER) } )
logger.info('Forcing download location to: %s' % mylar.CONFIG.QBITTORRENT_FOLDER)
if mylar.CONFIG.QBITTORRENT_LOADACTION == 'pause':
addargs.update( { 'paused': 'true' } )
logger.info('Attempting to add torrent in paused state')
if filepath.startswith('magnet'):
try:
tid = self.client.download_from_link(filepath, **addargs)
except Exception as e:
logger.error('Torrent not added')
return {'status': False, 'error': e}
else:
logger.debug('Successfully submitted for add as a magnet. Verifying item is now on client.')
else:
try:
torrent_content = open(filepath, 'rb')
tid = self.client.download_from_file(torrent_content, **addargs)
except Exception as e:
logger.error('Torrent not added')
return {'status': False, 'error': e}
else:
logger.debug('Successfully submitted for add via file. Verifying item is now on client.')
if mylar.CONFIG.QBITTORRENT_LOADACTION == 'force_start':
logger.info('Attempting to force start torrent')
try:
startit = self.client.force_start(hash)
logger.info('startit returned: %s' % startit)
except:
logger.warn('Unable to force start torrent - please check your client.')
else:
logger.info('Client default add action selected. Doing nothing.')
try:
time.sleep(5) # wait 5 in case it's not populated yet.
tinfo = self.get_torrent(hash)
except Exception as e:
logger.warn('Torrent was not added! Please check logs')
return {'status': False, 'error': e}
else:
logger.info('Torrent successfully added!')
filelist = self.client.get_torrent_files(hash)
#logger.info(filelist)
if len(filelist) == 1:
to_name = filelist[0]['name']
else:
to_name = tinfo['save_path']
torrent_info = {'hash': hash,
'files': filelist,
'name': to_name,
'total_filesize': tinfo['total_size'],
'folder': tinfo['save_path'],
'time_started': tinfo['addition_date'],
'label': mylar.CONFIG.QBITTORRENT_LABEL,
'status': True}
#logger.info(torrent_info)
return torrent_info
def get_the_hash(self, filepath):
import hashlib, StringIO
import bencode
# Open torrent file
torrent_file = open(filepath, "rb")
metainfo = bencode.decode(torrent_file.read())
info = metainfo['info']
thehash = hashlib.sha1(bencode.encode(info)).hexdigest().upper()
return thehash
| 7,159 | Python | .py | 142 | 35.457746 | 152 | 0.544946 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,275 | utorrent.py | evilhero_mylar/mylar/torrent/clients/utorrent.py | import os
from libs.utorrent.client import UTorrentClient
# Only compatible with uTorrent 3.0+
class TorrentClient(object):
def __init__(self):
self.conn = None
def connect(self, host, username, password):
if self.conn is not None:
return self.conn
if not host:
return False
if username and password:
self.conn = UTorrentClient(
host,
username,
password
)
else:
self.conn = UTorrentClient(host)
return self.conn
def find_torrent(self, hash):
try:
torrent_list = self.conn.list()[1]
for t in torrent_list['torrents']:
if t[0] == hash:
torrent = t
except Exception:
raise
return torrent if torrent else False
def get_torrent(self, torrent):
if not torrent[26]:
raise 'Only compatible with uTorrent 3.0+'
torrent_files = []
torrent_completed = False
torrent_directory = os.path.normpath(torrent[26])
try:
if torrent[4] == 1000:
torrent_completed = True
files = self.conn.getfiles(torrent[0])[1]['files'][1]
for f in files:
if not os.path.normpath(f[0]).startswith(torrent_directory):
file_path = os.path.join(torrent_directory, f[0].lstrip('/'))
else:
file_path = f[0]
torrent_files.append(file_path)
torrent_info = {
'hash': torrent[0],
'name': torrent[2],
'label': torrent[11] if torrent[11] else '',
'folder': torrent[26],
'completed': torrent_completed,
'files': torrent_files,
}
except Exception:
raise
return torrent_info
def start_torrent(self, torrent_hash):
return self.conn.start(torrent_hash)
def stop_torrent(self, torrent_hash):
return self.conn.stop(torrent_hash)
def delete_torrent(self, torrent):
deleted = []
try:
files = self.conn.getfiles(torrent[0])[1]['files'][1]
for f in files:
deleted.append(os.path.normpath(os.path.join(torrent[26], f[0])))
self.conn.removedata(torrent[0])
except Exception:
raise
return deleted
| 2,494 | Python | .py | 70 | 23.8 | 81 | 0.535029 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,276 | deluge.py | evilhero_mylar/mylar/torrent/clients/deluge.py | import os
import mylar
import base64
from mylar import logger, helpers
from deluge_client import DelugeRPCClient
class TorrentClient(object):
def __init__(self):
self.conn = None
def connect(self, host, username, password, test=False):
if self.conn is not None:
return self.connect
if not host:
return {'status': False, 'error': 'No host specified'}
if not username:
return {'status': False, 'error': 'No username specified'}
if not password:
return {'status': False, 'error': 'No password specified'}
# Get port from the config
host,portnr = host.split(':')
# logger.info('Connecting to ' + host + ':' + portnr + ' Username: ' + username + ' Password: ' + password )
try:
self.client = DelugeRPCClient(host,int(portnr),username,password)
except Exception as e:
logger.error('Could not create DelugeRPCClient Object %s' % e)
return {'status': False, 'error': e}
else:
try:
self.client.connect()
except Exception as e:
logger.error('Could not connect to Deluge: %s' % host)
return {'status': False, 'error': e}
else:
if test is True:
daemon_version = self.client.call('daemon.info')
libtorrent_version = self.client.call('core.get_libtorrent_version')
return {'status': True, 'daemon_version': daemon_version, 'libtorrent_version': libtorrent_version}
else:
return self.client
def find_torrent(self, hash):
logger.debug('Finding Torrent hash: ' + hash)
torrent_info = self.get_torrent(hash)
if torrent_info:
return True
else:
return False
def get_torrent(self, hash):
logger.debug('Getting Torrent info from hash: ' + hash)
try:
torrent_info = self.client.call('core.get_torrent_status', hash, '')
except Exception as e:
logger.error('Could not get torrent info for ' + hash)
return False
else:
if torrent_info is None:
torrent_info = False
return torrent_info
def start_torrent(self, hash):
try:
self.find_torrent(hash)
except Exception as e:
return False
else:
try:
self.client.call('core.resume_torrent', hash)
except Exception as e:
logger.error('Torrent failed to start ' + e)
else:
logger.info('Torrent ' + hash + ' was started')
return True
def stop_torrent(self, hash):
try:
self.client.find_torrent(hash)
except Exception as e:
logger.error('Torrent Not Found')
return False
else:
try:
self.client.call('core.pause_torrent', hash)
except Exception as e:
logger.error('Torrent failed to be stopped: ' + e)
return False
else:
logger.info('Torrent ' + hash + ' was stopped')
return True
def load_torrent(self, filepath):
options = {}
if mylar.CONFIG.DELUGE_DOWNLOAD_DIRECTORY:
options['download_location'] = mylar.CONFIG.DELUGE_DOWNLOAD_DIRECTORY
if mylar.CONFIG.DELUGE_DONE_DIRECTORY:
options['move_completed'] = 1
options['move_completed_path'] = mylar.CONFIG.DELUGE_DONE_DIRECTORY
if mylar.CONFIG.DELUGE_PAUSE:
options['add_paused'] = int(mylar.CONFIG.DELUGE_PAUSE)
logger.info('filepath to torrent file set to : ' + filepath)
torrent_id = False
if self.client.connected is True:
logger.info('Checking if Torrent Exists!')
if not filepath.startswith('magnet'):
torrentcontent = open(filepath, 'rb').read()
hash = str.lower(self.get_the_hash(filepath)) # Deluge expects a lower case hash
logger.debug('Torrent Hash (load_torrent): "' + hash + '"')
logger.debug('FileName (load_torrent): ' + str(os.path.basename(filepath)))
#Check if torrent already added
if self.find_torrent(str.lower(hash)):
logger.info('load_torrent: Torrent already exists!')
#should set something here to denote that it's already loaded, and then the failed download checker not run so it doesn't download
#multiple copies of the same issues that's already downloaded
else:
logger.info('Torrent not added yet, trying to add it now!')
try:
torrent_id = self.client.call('core.add_torrent_file', str(os.path.basename(filepath)), base64.encodestring(torrentcontent), options)
except Exception as e:
logger.debug('Torrent not added')
return False
else:
try:
torrent_id = self.client.call('core.add_torrent_magnet', str(filepath), options)
except Exception as e:
logger.debug('Torrent not added')
return False
# If label enabled put label on torrent in Deluge
if torrent_id and mylar.CONFIG.DELUGE_LABEL:
logger.info ('Setting label to ' + mylar.CONFIG.DELUGE_LABEL)
try:
self.client.call('label.set_torrent', torrent_id, mylar.CONFIG.DELUGE_LABEL)
except:
#if label isn't set, let's try and create one.
try:
self.client.call('label.add', mylar.CONFIG.DELUGE_LABEL)
self.client.call('label.set_torrent', torrent_id, mylar.CONFIG.DELUGE_LABEL)
except:
logger.warn('Unable to set label - Either try to create it manually within Deluge, and/or ensure there are no spaces, capitalization or special characters in label')
else:
logger.info('Succesfully set label to ' + mylar.CONFIG.DELUGE_LABEL)
try:
torrent_info = self.get_torrent(torrent_id)
logger.info('Double checking that the torrent was added.')
except Exception as e:
logger.warn('Torrent was not added! Please check logs')
return False
else:
logger.info('Torrent successfully added!')
return {'hash': torrent_info['hash'],
'label': mylar.CONFIG.DELUGE_LABEL,
'folder': torrent_info['save_path'],
'move path': torrent_info['move_completed_path'],
'total_filesize': torrent_info['total_size'],
'name': torrent_info['name'],
'files': torrent_info['files'],
'time_started': torrent_info['active_time'],
'pause': torrent_info['paused'],
'completed': torrent_info['is_finished']}
def delete_torrent(self, hash, removeData=False):
try:
self.client.find_torrent(hash)
except Exception as e:
logger.error('Torrent ' + hash + ' does not exist')
return False
else:
try:
self.client.call('core.remote_torrent', hash, removeData)
except Exception as e:
logger.error('Unable to delete torrent ' + hash)
return False
else:
logger.info('Torrent deleted ' + hash)
return True
def get_the_hash(self, filepath):
import hashlib, StringIO
import bencode
# Open torrent file
torrent_file = open(filepath, "rb")
metainfo = bencode.decode(torrent_file.read())
info = metainfo['info']
thehash = hashlib.sha1(bencode.encode(info)).hexdigest().upper()
logger.debug('Hash: ' + thehash)
return thehash
| 8,341 | Python | .py | 177 | 33.412429 | 189 | 0.552085 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,277 | variable.py | evilhero_mylar/mylar/torrent/helpers/variable.py | import os
def link(src, dst):
if os.name == 'nt':
import ctypes
if ctypes.windll.kernel32.CreateHardLinkW(unicode(dst), unicode(src), 0) == 0: raise ctypes.WinError()
else:
os.link(src, dst)
def symlink(src, dst):
if os.name == 'nt':
import ctypes
if ctypes.windll.kernel32.CreateSymbolicLinkW(unicode(dst), unicode(src), 1 if os.path.isdir(src) else 0) in [0, 1280]: raise ctypes.WinError()
else:
os.symlink(src, dst)
def is_rarfile(f):
import binascii
with open(f, "rb") as f:
byte = f.read(12)
spanned = binascii.hexlify(byte[10])
main = binascii.hexlify(byte[11])
if spanned == "01" and main == "01": # main rar archive in a set of archives
return True
elif spanned == "00" and main == "00": # single rar
return True
return False | 858 | Python | .py | 24 | 29.666667 | 151 | 0.628019 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,278 | fcgi.conf | evilhero_mylar/lib/cherrypy/test/fcgi.conf |
# Apache2 server conf file for testing CherryPy with mod_fcgid.
DocumentRoot "C:\Python25\Lib\site-packages\cherrypy\test"
ServerName 127.0.0.1
Listen 8080
LoadModule fastcgi_module modules/mod_fastcgi.dll
LoadModule rewrite_module modules/mod_rewrite.so
Options ExecCGI
SetHandler fastcgi-script
RewriteEngine On
RewriteRule ^(.*)$ /fastcgi.pyc [L]
FastCgiExternalServer "C:\\Python25\\Lib\\site-packages\\cherrypy\\test\\fastcgi.pyc" -host 127.0.0.1:4000
| 460 | Python | .cgi | 11 | 40.545455 | 106 | 0.818386 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,279 | modfcgid.py | evilhero_mylar/lib/cherrypy/test/modfcgid.py | """Wrapper for mod_fcgid, for use as a CherryPy HTTP server when testing.
To autostart fcgid, the "apache" executable or script must be
on your system path, or you must override the global APACHE_PATH.
On some platforms, "apache" may be called "apachectl", "apache2ctl",
or "httpd"--create a symlink to them if needed.
You'll also need the WSGIServer from flup.servers.
See http://projects.amor.org/misc/wiki/ModPythonGateway
KNOWN BUGS
==========
1. Apache processes Range headers automatically; CherryPy's truncated
output is then truncated again by Apache. See test_core.testRanges.
This was worked around in http://www.cherrypy.org/changeset/1319.
2. Apache does not allow custom HTTP methods like CONNECT as per the spec.
See test_core.testHTTPMethods.
3. Max request header and body settings do not work with Apache.
4. Apache replaces status "reason phrases" automatically. For example,
CherryPy may set "304 Not modified" but Apache will write out
"304 Not Modified" (capital "M").
5. Apache does not allow custom error codes as per the spec.
6. Apache (or perhaps modpython, or modpython_gateway) unquotes %xx in the
Request-URI too early.
7. mod_python will not read request bodies which use the "chunked"
transfer-coding (it passes REQUEST_CHUNKED_ERROR to ap_setup_client_block
instead of REQUEST_CHUNKED_DECHUNK, see Apache2's http_protocol.c and
mod_python's requestobject.c).
8. Apache will output a "Content-Length: 0" response header even if there's
no response entity body. This isn't really a bug; it just differs from
the CherryPy default.
"""
import os
curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import re
import sys
import time
import cherrypy
from cherrypy._cpcompat import ntob
from cherrypy.process import plugins, servers
from cherrypy.test import helper
def read_process(cmd, args=""):
pipein, pipeout = os.popen4("%s %s" % (cmd, args))
try:
firstline = pipeout.readline()
if (re.search(r"(not recognized|No such file|not found)", firstline,
re.IGNORECASE)):
raise IOError('%s must be on your system path.' % cmd)
output = firstline + pipeout.read()
finally:
pipeout.close()
return output
APACHE_PATH = "httpd"
CONF_PATH = "fcgi.conf"
conf_fcgid = """
# Apache2 server conf file for testing CherryPy with mod_fcgid.
DocumentRoot "%(root)s"
ServerName 127.0.0.1
Listen %(port)s
LoadModule fastcgi_module modules/mod_fastcgi.dll
LoadModule rewrite_module modules/mod_rewrite.so
Options ExecCGI
SetHandler fastcgi-script
RewriteEngine On
RewriteRule ^(.*)$ /fastcgi.pyc [L]
FastCgiExternalServer "%(server)s" -host 127.0.0.1:4000
"""
class ModFCGISupervisor(helper.LocalSupervisor):
using_apache = True
using_wsgi = True
template = conf_fcgid
def __str__(self):
return "FCGI Server on %s:%s" % (self.host, self.port)
def start(self, modulename):
cherrypy.server.httpserver = servers.FlupFCGIServer(
application=cherrypy.tree, bindAddress=('127.0.0.1', 4000))
cherrypy.server.httpserver.bind_addr = ('127.0.0.1', 4000)
# For FCGI, we both start apache...
self.start_apache()
# ...and our local server
helper.LocalServer.start(self, modulename)
def start_apache(self):
fcgiconf = CONF_PATH
if not os.path.isabs(fcgiconf):
fcgiconf = os.path.join(curdir, fcgiconf)
# Write the Apache conf file.
f = open(fcgiconf, 'wb')
try:
server = repr(os.path.join(curdir, 'fastcgi.pyc'))[1:-1]
output = self.template % {'port': self.port, 'root': curdir,
'server': server}
output = ntob(output.replace('\r\n', '\n'))
f.write(output)
finally:
f.close()
result = read_process(APACHE_PATH, "-k start -f %s" % fcgiconf)
if result:
print(result)
def stop(self):
"""Gracefully shutdown a server that is serving forever."""
read_process(APACHE_PATH, "-k stop")
helper.LocalServer.stop(self)
def sync_apps(self):
cherrypy.server.httpserver.fcgiserver.application = self.get_app()
| 4,308 | Python | .cgi | 101 | 36.623762 | 77 | 0.691528 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,280 | fastcgi.conf | evilhero_mylar/lib/cherrypy/test/fastcgi.conf |
# Apache2 server conf file for testing CherryPy with mod_fastcgi.
# fumanchu: I had to hard-code paths due to crazy Debian layouts :(
ServerRoot /usr/lib/apache2
User #1000
ErrorLog /usr/lib/python2.5/site-packages/cproot/trunk/cherrypy/test/mod_fastcgi.error.log
DocumentRoot "/usr/lib/python2.5/site-packages/cproot/trunk/cherrypy/test"
ServerName 127.0.0.1
Listen 8080
LoadModule fastcgi_module modules/mod_fastcgi.so
LoadModule rewrite_module modules/mod_rewrite.so
Options +ExecCGI
SetHandler fastcgi-script
RewriteEngine On
RewriteRule ^(.*)$ /fastcgi.pyc [L]
FastCgiExternalServer "/usr/lib/python2.5/site-packages/cproot/trunk/cherrypy/test/fastcgi.pyc" -host 127.0.0.1:4000
| 686 | Python | .cgi | 15 | 44.533333 | 116 | 0.820359 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,281 | modfastcgi.py | evilhero_mylar/lib/cherrypy/test/modfastcgi.py | """Wrapper for mod_fastcgi, for use as a CherryPy HTTP server when testing.
To autostart fastcgi, the "apache" executable or script must be
on your system path, or you must override the global APACHE_PATH.
On some platforms, "apache" may be called "apachectl", "apache2ctl",
or "httpd"--create a symlink to them if needed.
You'll also need the WSGIServer from flup.servers.
See http://projects.amor.org/misc/wiki/ModPythonGateway
KNOWN BUGS
==========
1. Apache processes Range headers automatically; CherryPy's truncated
output is then truncated again by Apache. See test_core.testRanges.
This was worked around in http://www.cherrypy.org/changeset/1319.
2. Apache does not allow custom HTTP methods like CONNECT as per the spec.
See test_core.testHTTPMethods.
3. Max request header and body settings do not work with Apache.
4. Apache replaces status "reason phrases" automatically. For example,
CherryPy may set "304 Not modified" but Apache will write out
"304 Not Modified" (capital "M").
5. Apache does not allow custom error codes as per the spec.
6. Apache (or perhaps modpython, or modpython_gateway) unquotes %xx in the
Request-URI too early.
7. mod_python will not read request bodies which use the "chunked"
transfer-coding (it passes REQUEST_CHUNKED_ERROR to ap_setup_client_block
instead of REQUEST_CHUNKED_DECHUNK, see Apache2's http_protocol.c and
mod_python's requestobject.c).
8. Apache will output a "Content-Length: 0" response header even if there's
no response entity body. This isn't really a bug; it just differs from
the CherryPy default.
"""
import os
curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import re
import sys
import time
import cherrypy
from cherrypy.process import plugins, servers
from cherrypy.test import helper
def read_process(cmd, args=""):
pipein, pipeout = os.popen4("%s %s" % (cmd, args))
try:
firstline = pipeout.readline()
if (re.search(r"(not recognized|No such file|not found)", firstline,
re.IGNORECASE)):
raise IOError('%s must be on your system path.' % cmd)
output = firstline + pipeout.read()
finally:
pipeout.close()
return output
APACHE_PATH = "apache2ctl"
CONF_PATH = "fastcgi.conf"
conf_fastcgi = """
# Apache2 server conf file for testing CherryPy with mod_fastcgi.
# fumanchu: I had to hard-code paths due to crazy Debian layouts :(
ServerRoot /usr/lib/apache2
User #1000
ErrorLog %(root)s/mod_fastcgi.error.log
DocumentRoot "%(root)s"
ServerName 127.0.0.1
Listen %(port)s
LoadModule fastcgi_module modules/mod_fastcgi.so
LoadModule rewrite_module modules/mod_rewrite.so
Options +ExecCGI
SetHandler fastcgi-script
RewriteEngine On
RewriteRule ^(.*)$ /fastcgi.pyc [L]
FastCgiExternalServer "%(server)s" -host 127.0.0.1:4000
"""
def erase_script_name(environ, start_response):
environ['SCRIPT_NAME'] = ''
return cherrypy.tree(environ, start_response)
class ModFCGISupervisor(helper.LocalWSGISupervisor):
httpserver_class = "cherrypy.process.servers.FlupFCGIServer"
using_apache = True
using_wsgi = True
template = conf_fastcgi
def __str__(self):
return "FCGI Server on %s:%s" % (self.host, self.port)
def start(self, modulename):
cherrypy.server.httpserver = servers.FlupFCGIServer(
application=erase_script_name, bindAddress=('127.0.0.1', 4000))
cherrypy.server.httpserver.bind_addr = ('127.0.0.1', 4000)
cherrypy.server.socket_port = 4000
# For FCGI, we both start apache...
self.start_apache()
# ...and our local server
cherrypy.engine.start()
self.sync_apps()
def start_apache(self):
fcgiconf = CONF_PATH
if not os.path.isabs(fcgiconf):
fcgiconf = os.path.join(curdir, fcgiconf)
# Write the Apache conf file.
f = open(fcgiconf, 'wb')
try:
server = repr(os.path.join(curdir, 'fastcgi.pyc'))[1:-1]
output = self.template % {'port': self.port, 'root': curdir,
'server': server}
output = output.replace('\r\n', '\n')
f.write(output)
finally:
f.close()
result = read_process(APACHE_PATH, "-k start -f %s" % fcgiconf)
if result:
print(result)
def stop(self):
"""Gracefully shutdown a server that is serving forever."""
read_process(APACHE_PATH, "-k stop")
helper.LocalWSGISupervisor.stop(self)
def sync_apps(self):
cherrypy.server.httpserver.fcgiserver.application = self.get_app(erase_script_name)
| 4,709 | Python | .cgi | 110 | 36.927273 | 91 | 0.696295 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,282 | apache-fcgi.conf | evilhero_mylar/lib/cherrypy/scaffold/apache-fcgi.conf | # Apache2 server conf file for using CherryPy with mod_fcgid.
# This doesn't have to be "C:/", but it has to be a directory somewhere, and
# MUST match the directory used in the FastCgiExternalServer directive, below.
DocumentRoot "C:/"
ServerName 127.0.0.1
Listen 80
LoadModule fastcgi_module modules/mod_fastcgi.dll
LoadModule rewrite_module modules/mod_rewrite.so
Options ExecCGI
SetHandler fastcgi-script
RewriteEngine On
# Send requests for any URI to our fastcgi handler.
RewriteRule ^(.*)$ /fastcgi.pyc [L]
# The FastCgiExternalServer directive defines filename as an external FastCGI application.
# If filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.
# The filename does not have to exist in the local filesystem. URIs that Apache resolves to this
# filename will be handled by this external FastCGI application.
FastCgiExternalServer "C:/fastcgi.pyc" -host 127.0.0.1:8088 | 929 | Python | .cgi | 18 | 50.444444 | 98 | 0.805066 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,283 | scgi.py | evilhero_mylar/lib/rtorrent/lib/xmlrpc/clients/scgi.py | #!/usr/bin/python
# rtorrent_xmlrpc
# (c) 2011 Roger Que <alerante@bellsouth.net>
#
# Modified portions:
# (c) 2013 Dean Gardiner <gardiner91@gmail.com>
#
# Python module for interacting with rtorrent's XML-RPC interface
# directly over SCGI, instead of through an HTTP server intermediary.
# Inspired by Glenn Washburn's xmlrpc2scgi.py [1], but subclasses the
# built-in xmlrpclib classes so that it is compatible with features
# such as MultiCall objects.
#
# [1] <http://libtorrent.rakshasa.no/wiki/UtilsXmlrpc2scgi>
#
# Usage: server = SCGIServerProxy('scgi://localhost:7000/')
# server = SCGIServerProxy('scgi:///path/to/scgi.sock')
# print server.system.listMethods()
# mc = xmlrpclib.MultiCall(server)
# mc.get_up_rate()
# mc.get_down_rate()
# print mc()
#
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
#
# You must obey the GNU General Public License in all respects for
# all of the code used other than OpenSSL. If you modify file(s)
# with this exception, you may extend this exception to your version
# of the file(s), but you are not obligated to do so. If you do not
# wish to do so, delete this exception statement from your version.
# If you delete this exception statement from all source files in the
# program, then also delete it here.
#
#
#
# Portions based on Python's xmlrpclib:
#
# Copyright (c) 1999-2002 by Secret Labs AB
# Copyright (c) 1999-2002 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
import urllib
import xmlrpclib
from rtorrent.lib.xmlrpc.transports.scgi import SCGITransport
class SCGIServerProxy(xmlrpclib.ServerProxy):
def __init__(self, uri, transport=None, encoding=None, verbose=False,
allow_none=False, use_datetime=False):
type, uri = urllib.splittype(uri)
if type not in ('scgi'):
raise IOError('unsupported XML-RPC protocol')
self.__host, self.__handler = urllib.splithost(uri)
if not self.__handler:
self.__handler = '/'
if transport is None:
transport = SCGITransport(use_datetime=use_datetime)
self.__transport = transport
self.__encoding = encoding
self.__verbose = verbose
self.__allow_none = allow_none
def __close(self):
self.__transport.close()
def __request(self, methodname, params):
# call a method on the remote server
request = xmlrpclib.dumps(params, methodname, encoding=self.__encoding,
allow_none=self.__allow_none)
response = self.__transport.request(
self.__host,
self.__handler,
request,
verbose=self.__verbose
)
if len(response) == 1:
response = response[0]
return response
def __repr__(self):
return (
"<SCGIServerProxy for %s%s>" %
(self.__host, self.__handler)
)
__str__ = __repr__
def __getattr__(self, name):
# magic method dispatcher
return xmlrpclib._Method(self.__request, name)
# note: to call a remote object with an non-standard name, use
# result getattr(server, "strange-python-name")(args)
def __call__(self, attr):
"""A workaround to get special attributes on the ServerProxy
without interfering with the magic __getattr__
"""
if attr == "close":
return self.__close
elif attr == "transport":
return self.__transport
raise AttributeError("Attribute %r not found" % (attr,))
| 5,670 | Python | .cgi | 134 | 37.865672 | 79 | 0.707503 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,284 | scgi.py | evilhero_mylar/lib/rtorrent/lib/xmlrpc/transports/scgi.py | #!/usr/bin/python
# rtorrent_xmlrpc
# (c) 2011 Roger Que <alerante@bellsouth.net>
#
# Modified portions:
# (c) 2013 Dean Gardiner <gardiner91@gmail.com>
#
# Python module for interacting with rtorrent's XML-RPC interface
# directly over SCGI, instead of through an HTTP server intermediary.
# Inspired by Glenn Washburn's xmlrpc2scgi.py [1], but subclasses the
# built-in xmlrpclib classes so that it is compatible with features
# such as MultiCall objects.
#
# [1] <http://libtorrent.rakshasa.no/wiki/UtilsXmlrpc2scgi>
#
# Usage: server = SCGIServerProxy('scgi://localhost:7000/')
# server = SCGIServerProxy('scgi:///path/to/scgi.sock')
# print server.system.listMethods()
# mc = xmlrpclib.MultiCall(server)
# mc.get_up_rate()
# mc.get_down_rate()
# print mc()
#
#
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
#
# You must obey the GNU General Public License in all respects for
# all of the code used other than OpenSSL. If you modify file(s)
# with this exception, you may extend this exception to your version
# of the file(s), but you are not obligated to do so. If you do not
# wish to do so, delete this exception statement from your version.
# If you delete this exception statement from all source files in the
# program, then also delete it here.
#
#
#
# Portions based on Python's xmlrpclib:
#
# Copyright (c) 1999-2002 by Secret Labs AB
# Copyright (c) 1999-2002 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
import errno
import httplib
import re
import socket
import urllib
import xmlrpclib
class SCGITransport(xmlrpclib.Transport):
# Added request() from Python 2.7 xmlrpclib here to backport to Python 2.6
def request(self, host, handler, request_body, verbose=0):
#retry request once if cached connection has gone cold
for i in (0, 1):
try:
return self.single_request(host, handler, request_body, verbose)
except socket.error, e:
if i or e.errno not in (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE):
raise
except httplib.BadStatusLine: #close after we sent request
if i:
raise
def single_request(self, host, handler, request_body, verbose=0):
# Add SCGI headers to the request.
headers = {'CONTENT_LENGTH': str(len(request_body)), 'SCGI': '1'}
header = '\x00'.join(('%s\x00%s' % item for item in headers.iteritems())) + '\x00'
header = '%d:%s' % (len(header), header)
request_body = '%s,%s' % (header, request_body)
sock = None
try:
if host:
host, port = urllib.splitport(host)
addrinfo = socket.getaddrinfo(host, int(port), socket.AF_INET,
socket.SOCK_STREAM)
sock = socket.socket(*addrinfo[0][:3])
sock.connect(addrinfo[0][4])
else:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(handler)
self.verbose = verbose
sock.send(request_body)
return self.parse_response(sock.makefile())
finally:
if sock:
sock.close()
def parse_response(self, response):
p, u = self.getparser()
response_body = ''
while True:
data = response.read(1024)
if not data:
break
response_body += data
# Remove SCGI headers from the response.
response_header, response_body = re.split(r'\n\s*?\n', response_body,
maxsplit=1)
if self.verbose:
print 'body:', repr(response_body)
p.feed(response_body)
p.close()
return u.close()
| 5,943 | Python | .cgi | 139 | 37.064748 | 91 | 0.686247 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,285 | modfcgid.py | evilhero_mylar/lib/cherrypy/test/modfcgid.py | """Wrapper for mod_fcgid, for use as a CherryPy HTTP server when testing.
To autostart fcgid, the "apache" executable or script must be
on your system path, or you must override the global APACHE_PATH.
On some platforms, "apache" may be called "apachectl", "apache2ctl",
or "httpd"--create a symlink to them if needed.
You'll also need the WSGIServer from flup.servers.
See http://projects.amor.org/misc/wiki/ModPythonGateway
KNOWN BUGS
==========
1. Apache processes Range headers automatically; CherryPy's truncated
output is then truncated again by Apache. See test_core.testRanges.
This was worked around in http://www.cherrypy.org/changeset/1319.
2. Apache does not allow custom HTTP methods like CONNECT as per the spec.
See test_core.testHTTPMethods.
3. Max request header and body settings do not work with Apache.
4. Apache replaces status "reason phrases" automatically. For example,
CherryPy may set "304 Not modified" but Apache will write out
"304 Not Modified" (capital "M").
5. Apache does not allow custom error codes as per the spec.
6. Apache (or perhaps modpython, or modpython_gateway) unquotes %xx in the
Request-URI too early.
7. mod_python will not read request bodies which use the "chunked"
transfer-coding (it passes REQUEST_CHUNKED_ERROR to ap_setup_client_block
instead of REQUEST_CHUNKED_DECHUNK, see Apache2's http_protocol.c and
mod_python's requestobject.c).
8. Apache will output a "Content-Length: 0" response header even if there's
no response entity body. This isn't really a bug; it just differs from
the CherryPy default.
"""
import os
curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import re
import sys
import time
import cherrypy
from cherrypy._cpcompat import ntob
from cherrypy.process import plugins, servers
from cherrypy.test import helper
def read_process(cmd, args=""):
pipein, pipeout = os.popen4("%s %s" % (cmd, args))
try:
firstline = pipeout.readline()
if (re.search(r"(not recognized|No such file|not found)", firstline,
re.IGNORECASE)):
raise IOError('%s must be on your system path.' % cmd)
output = firstline + pipeout.read()
finally:
pipeout.close()
return output
APACHE_PATH = "httpd"
CONF_PATH = "fcgi.conf"
conf_fcgid = """
# Apache2 server conf file for testing CherryPy with mod_fcgid.
DocumentRoot "%(root)s"
ServerName 127.0.0.1
Listen %(port)s
LoadModule fastcgi_module modules/mod_fastcgi.dll
LoadModule rewrite_module modules/mod_rewrite.so
Options ExecCGI
SetHandler fastcgi-script
RewriteEngine On
RewriteRule ^(.*)$ /fastcgi.pyc [L]
FastCgiExternalServer "%(server)s" -host 127.0.0.1:4000
"""
class ModFCGISupervisor(helper.LocalSupervisor):
using_apache = True
using_wsgi = True
template = conf_fcgid
def __str__(self):
return "FCGI Server on %s:%s" % (self.host, self.port)
def start(self, modulename):
cherrypy.server.httpserver = servers.FlupFCGIServer(
application=cherrypy.tree, bindAddress=('127.0.0.1', 4000))
cherrypy.server.httpserver.bind_addr = ('127.0.0.1', 4000)
# For FCGI, we both start apache...
self.start_apache()
# ...and our local server
helper.LocalServer.start(self, modulename)
def start_apache(self):
fcgiconf = CONF_PATH
if not os.path.isabs(fcgiconf):
fcgiconf = os.path.join(curdir, fcgiconf)
# Write the Apache conf file.
f = open(fcgiconf, 'wb')
try:
server = repr(os.path.join(curdir, 'fastcgi.pyc'))[1:-1]
output = self.template % {'port': self.port, 'root': curdir,
'server': server}
output = ntob(output.replace('\r\n', '\n'))
f.write(output)
finally:
f.close()
result = read_process(APACHE_PATH, "-k start -f %s" % fcgiconf)
if result:
print(result)
def stop(self):
"""Gracefully shutdown a server that is serving forever."""
read_process(APACHE_PATH, "-k stop")
helper.LocalServer.stop(self)
def sync_apps(self):
cherrypy.server.httpserver.fcgiserver.application = self.get_app()
| 4,308 | Python | .fcgi | 101 | 36.623762 | 77 | 0.691528 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,286 | apache-fcgi.conf | evilhero_mylar/lib/cherrypy/scaffold/apache-fcgi.conf | # Apache2 server conf file for using CherryPy with mod_fcgid.
# This doesn't have to be "C:/", but it has to be a directory somewhere, and
# MUST match the directory used in the FastCgiExternalServer directive, below.
DocumentRoot "C:/"
ServerName 127.0.0.1
Listen 80
LoadModule fastcgi_module modules/mod_fastcgi.dll
LoadModule rewrite_module modules/mod_rewrite.so
Options ExecCGI
SetHandler fastcgi-script
RewriteEngine On
# Send requests for any URI to our fastcgi handler.
RewriteRule ^(.*)$ /fastcgi.pyc [L]
# The FastCgiExternalServer directive defines filename as an external FastCGI application.
# If filename does not begin with a slash (/) then it is assumed to be relative to the ServerRoot.
# The filename does not have to exist in the local filesystem. URIs that Apache resolves to this
# filename will be handled by this external FastCGI application.
FastCgiExternalServer "C:/fastcgi.pyc" -host 127.0.0.1:8088 | 929 | Python | .fcgi | 18 | 50.444444 | 98 | 0.805066 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,287 | _cpwsgi_server.py | evilhero_mylar/lib/cherrypy/_cpwsgi_server.py | """WSGI server interface (see PEP 333). This adds some CP-specific bits to
the framework-agnostic wsgiserver package.
"""
import sys
import cherrypy
from cherrypy import wsgiserver
class CPWSGIServer(wsgiserver.CherryPyWSGIServer):
"""Wrapper for wsgiserver.CherryPyWSGIServer.
wsgiserver has been designed to not reference CherryPy in any way,
so that it can be used in other frameworks and applications. Therefore,
we wrap it here, so we can set our own mount points from cherrypy.tree
and apply some attributes from config -> cherrypy.server -> wsgiserver.
"""
def __init__(self, server_adapter=cherrypy.server):
self.server_adapter = server_adapter
self.max_request_header_size = (
self.server_adapter.max_request_header_size or 0
)
self.max_request_body_size = (
self.server_adapter.max_request_body_size or 0
)
server_name = (self.server_adapter.socket_host or
self.server_adapter.socket_file or
None)
self.wsgi_version = self.server_adapter.wsgi_version
s = wsgiserver.CherryPyWSGIServer
s.__init__(self, server_adapter.bind_addr, cherrypy.tree,
self.server_adapter.thread_pool,
server_name,
max=self.server_adapter.thread_pool_max,
request_queue_size=self.server_adapter.socket_queue_size,
timeout=self.server_adapter.socket_timeout,
shutdown_timeout=self.server_adapter.shutdown_timeout,
accepted_queue_size=self.server_adapter.accepted_queue_size,
accepted_queue_timeout=self.server_adapter.accepted_queue_timeout,
)
self.protocol = self.server_adapter.protocol_version
self.nodelay = self.server_adapter.nodelay
if sys.version_info >= (3, 0):
ssl_module = self.server_adapter.ssl_module or 'builtin'
else:
ssl_module = self.server_adapter.ssl_module or 'pyopenssl'
if self.server_adapter.ssl_context:
adapter_class = wsgiserver.get_ssl_adapter_class(ssl_module)
self.ssl_adapter = adapter_class(
self.server_adapter.ssl_certificate,
self.server_adapter.ssl_private_key,
self.server_adapter.ssl_certificate_chain)
self.ssl_adapter.context = self.server_adapter.ssl_context
elif self.server_adapter.ssl_certificate:
adapter_class = wsgiserver.get_ssl_adapter_class(ssl_module)
self.ssl_adapter = adapter_class(
self.server_adapter.ssl_certificate,
self.server_adapter.ssl_private_key,
self.server_adapter.ssl_certificate_chain)
self.stats['Enabled'] = getattr(
self.server_adapter, 'statistics', False)
def error_log(self, msg="", level=20, traceback=False):
cherrypy.engine.log(msg, level, traceback)
| 3,023 | Python | .wsgi | 59 | 39.864407 | 85 | 0.648154 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,288 | _cpwsgi.py | evilhero_mylar/lib/cherrypy/_cpwsgi.py | """WSGI interface (see PEP 333 and 3333).
Note that WSGI environ keys and values are 'native strings'; that is,
whatever the type of "" is. For Python 2, that's a byte string; for Python 3,
it's a unicode string. But PEP 3333 says: "even if Python's str type is
actually Unicode "under the hood", the content of native strings must
still be translatable to bytes via the Latin-1 encoding!"
"""
import sys as _sys
import cherrypy as _cherrypy
from cherrypy._cpcompat import BytesIO, bytestr, ntob, ntou, py3k, unicodestr
from cherrypy import _cperror
from cherrypy.lib import httputil
from cherrypy.lib import is_closable_iterator
def downgrade_wsgi_ux_to_1x(environ):
"""Return a new environ dict for WSGI 1.x from the given WSGI u.x environ.
"""
env1x = {}
url_encoding = environ[ntou('wsgi.url_encoding')]
for k, v in list(environ.items()):
if k in [ntou('PATH_INFO'), ntou('SCRIPT_NAME'), ntou('QUERY_STRING')]:
v = v.encode(url_encoding)
elif isinstance(v, unicodestr):
v = v.encode('ISO-8859-1')
env1x[k.encode('ISO-8859-1')] = v
return env1x
class VirtualHost(object):
"""Select a different WSGI application based on the Host header.
This can be useful when running multiple sites within one CP server.
It allows several domains to point to different applications. For example::
root = Root()
RootApp = cherrypy.Application(root)
Domain2App = cherrypy.Application(root)
SecureApp = cherrypy.Application(Secure())
vhost = cherrypy._cpwsgi.VirtualHost(RootApp,
domains={'www.domain2.example': Domain2App,
'www.domain2.example:443': SecureApp,
})
cherrypy.tree.graft(vhost)
"""
default = None
"""Required. The default WSGI application."""
use_x_forwarded_host = True
"""If True (the default), any "X-Forwarded-Host"
request header will be used instead of the "Host" header. This
is commonly added by HTTP servers (such as Apache) when proxying."""
domains = {}
"""A dict of {host header value: application} pairs.
The incoming "Host" request header is looked up in this dict,
and, if a match is found, the corresponding WSGI application
will be called instead of the default. Note that you often need
separate entries for "example.com" and "www.example.com".
In addition, "Host" headers may contain the port number.
"""
def __init__(self, default, domains=None, use_x_forwarded_host=True):
self.default = default
self.domains = domains or {}
self.use_x_forwarded_host = use_x_forwarded_host
def __call__(self, environ, start_response):
domain = environ.get('HTTP_HOST', '')
if self.use_x_forwarded_host:
domain = environ.get("HTTP_X_FORWARDED_HOST", domain)
nextapp = self.domains.get(domain)
if nextapp is None:
nextapp = self.default
return nextapp(environ, start_response)
class InternalRedirector(object):
"""WSGI middleware that handles raised cherrypy.InternalRedirect."""
def __init__(self, nextapp, recursive=False):
self.nextapp = nextapp
self.recursive = recursive
def __call__(self, environ, start_response):
redirections = []
while True:
environ = environ.copy()
try:
return self.nextapp(environ, start_response)
except _cherrypy.InternalRedirect:
ir = _sys.exc_info()[1]
sn = environ.get('SCRIPT_NAME', '')
path = environ.get('PATH_INFO', '')
qs = environ.get('QUERY_STRING', '')
# Add the *previous* path_info + qs to redirections.
old_uri = sn + path
if qs:
old_uri += "?" + qs
redirections.append(old_uri)
if not self.recursive:
# Check to see if the new URI has been redirected to
# already
new_uri = sn + ir.path
if ir.query_string:
new_uri += "?" + ir.query_string
if new_uri in redirections:
ir.request.close()
raise RuntimeError("InternalRedirector visited the "
"same URL twice: %r" % new_uri)
# Munge the environment and try again.
environ['REQUEST_METHOD'] = "GET"
environ['PATH_INFO'] = ir.path
environ['QUERY_STRING'] = ir.query_string
environ['wsgi.input'] = BytesIO()
environ['CONTENT_LENGTH'] = "0"
environ['cherrypy.previous_request'] = ir.request
class ExceptionTrapper(object):
"""WSGI middleware that traps exceptions."""
def __init__(self, nextapp, throws=(KeyboardInterrupt, SystemExit)):
self.nextapp = nextapp
self.throws = throws
def __call__(self, environ, start_response):
return _TrappedResponse(
self.nextapp,
environ,
start_response,
self.throws
)
class _TrappedResponse(object):
response = iter([])
def __init__(self, nextapp, environ, start_response, throws):
self.nextapp = nextapp
self.environ = environ
self.start_response = start_response
self.throws = throws
self.started_response = False
self.response = self.trap(
self.nextapp, self.environ, self.start_response)
self.iter_response = iter(self.response)
def __iter__(self):
self.started_response = True
return self
if py3k:
def __next__(self):
return self.trap(next, self.iter_response)
else:
def next(self):
return self.trap(self.iter_response.next)
def close(self):
if hasattr(self.response, 'close'):
self.response.close()
def trap(self, func, *args, **kwargs):
try:
return func(*args, **kwargs)
except self.throws:
raise
except StopIteration:
raise
except:
tb = _cperror.format_exc()
#print('trapped (started %s):' % self.started_response, tb)
_cherrypy.log(tb, severity=40)
if not _cherrypy.request.show_tracebacks:
tb = ""
s, h, b = _cperror.bare_error(tb)
if py3k:
# What fun.
s = s.decode('ISO-8859-1')
h = [(k.decode('ISO-8859-1'), v.decode('ISO-8859-1'))
for k, v in h]
if self.started_response:
# Empty our iterable (so future calls raise StopIteration)
self.iter_response = iter([])
else:
self.iter_response = iter(b)
try:
self.start_response(s, h, _sys.exc_info())
except:
# "The application must not trap any exceptions raised by
# start_response, if it called start_response with exc_info.
# Instead, it should allow such exceptions to propagate
# back to the server or gateway."
# But we still log and call close() to clean up ourselves.
_cherrypy.log(traceback=True, severity=40)
raise
if self.started_response:
return ntob("").join(b)
else:
return b
# WSGI-to-CP Adapter #
class AppResponse(object):
"""WSGI response iterable for CherryPy applications."""
def __init__(self, environ, start_response, cpapp):
self.cpapp = cpapp
try:
if not py3k:
if environ.get(ntou('wsgi.version')) == (ntou('u'), 0):
environ = downgrade_wsgi_ux_to_1x(environ)
self.environ = environ
self.run()
r = _cherrypy.serving.response
outstatus = r.output_status
if not isinstance(outstatus, bytestr):
raise TypeError("response.output_status is not a byte string.")
outheaders = []
for k, v in r.header_list:
if not isinstance(k, bytestr):
raise TypeError(
"response.header_list key %r is not a byte string." %
k)
if not isinstance(v, bytestr):
raise TypeError(
"response.header_list value %r is not a byte string." %
v)
outheaders.append((k, v))
if py3k:
# According to PEP 3333, when using Python 3, the response
# status and headers must be bytes masquerading as unicode;
# that is, they must be of type "str" but are restricted to
# code points in the "latin-1" set.
outstatus = outstatus.decode('ISO-8859-1')
outheaders = [(k.decode('ISO-8859-1'), v.decode('ISO-8859-1'))
for k, v in outheaders]
self.iter_response = iter(r.body)
self.write = start_response(outstatus, outheaders)
except:
self.close()
raise
def __iter__(self):
return self
if py3k:
def __next__(self):
return next(self.iter_response)
else:
def next(self):
return self.iter_response.next()
def close(self):
"""Close and de-reference the current request and response. (Core)"""
streaming = _cherrypy.serving.response.stream
self.cpapp.release_serving()
# We avoid the expense of examining the iterator to see if it's
# closable unless we are streaming the response, as that's the
# only situation where we are going to have an iterator which
# may not have been exhausted yet.
if streaming and is_closable_iterator(self.iter_response):
iter_close = self.iter_response.close
try:
iter_close()
except Exception:
_cherrypy.log(traceback=True, severity=40)
def run(self):
"""Create a Request object using environ."""
env = self.environ.get
local = httputil.Host('', int(env('SERVER_PORT', 80)),
env('SERVER_NAME', ''))
remote = httputil.Host(env('REMOTE_ADDR', ''),
int(env('REMOTE_PORT', -1) or -1),
env('REMOTE_HOST', ''))
scheme = env('wsgi.url_scheme')
sproto = env('ACTUAL_SERVER_PROTOCOL', "HTTP/1.1")
request, resp = self.cpapp.get_serving(local, remote, scheme, sproto)
# LOGON_USER is served by IIS, and is the name of the
# user after having been mapped to a local account.
# Both IIS and Apache set REMOTE_USER, when possible.
request.login = env('LOGON_USER') or env('REMOTE_USER') or None
request.multithread = self.environ['wsgi.multithread']
request.multiprocess = self.environ['wsgi.multiprocess']
request.wsgi_environ = self.environ
request.prev = env('cherrypy.previous_request', None)
meth = self.environ['REQUEST_METHOD']
path = httputil.urljoin(self.environ.get('SCRIPT_NAME', ''),
self.environ.get('PATH_INFO', ''))
qs = self.environ.get('QUERY_STRING', '')
if py3k:
# This isn't perfect; if the given PATH_INFO is in the
# wrong encoding, it may fail to match the appropriate config
# section URI. But meh.
old_enc = self.environ.get('wsgi.url_encoding', 'ISO-8859-1')
new_enc = self.cpapp.find_config(self.environ.get('PATH_INFO', ''),
"request.uri_encoding", 'utf-8')
if new_enc.lower() != old_enc.lower():
# Even though the path and qs are unicode, the WSGI server
# is required by PEP 3333 to coerce them to ISO-8859-1
# masquerading as unicode. So we have to encode back to
# bytes and then decode again using the "correct" encoding.
try:
u_path = path.encode(old_enc).decode(new_enc)
u_qs = qs.encode(old_enc).decode(new_enc)
except (UnicodeEncodeError, UnicodeDecodeError):
# Just pass them through without transcoding and hope.
pass
else:
# Only set transcoded values if they both succeed.
path = u_path
qs = u_qs
rproto = self.environ.get('SERVER_PROTOCOL')
headers = self.translate_headers(self.environ)
rfile = self.environ['wsgi.input']
request.run(meth, path, qs, rproto, headers, rfile)
headerNames = {'HTTP_CGI_AUTHORIZATION': 'Authorization',
'CONTENT_LENGTH': 'Content-Length',
'CONTENT_TYPE': 'Content-Type',
'REMOTE_HOST': 'Remote-Host',
'REMOTE_ADDR': 'Remote-Addr',
}
def translate_headers(self, environ):
"""Translate CGI-environ header names to HTTP header names."""
for cgiName in environ:
# We assume all incoming header keys are uppercase already.
if cgiName in self.headerNames:
yield self.headerNames[cgiName], environ[cgiName]
elif cgiName[:5] == "HTTP_":
# Hackish attempt at recovering original header names.
translatedHeader = cgiName[5:].replace("_", "-")
yield translatedHeader, environ[cgiName]
class CPWSGIApp(object):
"""A WSGI application object for a CherryPy Application."""
pipeline = [('ExceptionTrapper', ExceptionTrapper),
('InternalRedirector', InternalRedirector),
]
"""A list of (name, wsgiapp) pairs. Each 'wsgiapp' MUST be a
constructor that takes an initial, positional 'nextapp' argument,
plus optional keyword arguments, and returns a WSGI application
(that takes environ and start_response arguments). The 'name' can
be any you choose, and will correspond to keys in self.config."""
head = None
"""Rather than nest all apps in the pipeline on each call, it's only
done the first time, and the result is memoized into self.head. Set
this to None again if you change self.pipeline after calling self."""
config = {}
"""A dict whose keys match names listed in the pipeline. Each
value is a further dict which will be passed to the corresponding
named WSGI callable (from the pipeline) as keyword arguments."""
response_class = AppResponse
"""The class to instantiate and return as the next app in the WSGI chain.
"""
def __init__(self, cpapp, pipeline=None):
self.cpapp = cpapp
self.pipeline = self.pipeline[:]
if pipeline:
self.pipeline.extend(pipeline)
self.config = self.config.copy()
def tail(self, environ, start_response):
"""WSGI application callable for the actual CherryPy application.
You probably shouldn't call this; call self.__call__ instead,
so that any WSGI middleware in self.pipeline can run first.
"""
return self.response_class(environ, start_response, self.cpapp)
def __call__(self, environ, start_response):
head = self.head
if head is None:
# Create and nest the WSGI apps in our pipeline (in reverse order).
# Then memoize the result in self.head.
head = self.tail
for name, callable in self.pipeline[::-1]:
conf = self.config.get(name, {})
head = callable(head, **conf)
self.head = head
return head(environ, start_response)
def namespace_handler(self, k, v):
"""Config handler for the 'wsgi' namespace."""
if k == "pipeline":
# Note this allows multiple 'wsgi.pipeline' config entries
# (but each entry will be processed in a 'random' order).
# It should also allow developers to set default middleware
# in code (passed to self.__init__) that deployers can add to
# (but not remove) via config.
self.pipeline.extend(v)
elif k == "response_class":
self.response_class = v
else:
name, arg = k.split(".", 1)
bucket = self.config.setdefault(name, {})
bucket[arg] = v
| 16,870 | Python | .wsgi | 361 | 34.947368 | 79 | 0.580331 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,289 | test_wsgi_ns.py | evilhero_mylar/lib/cherrypy/test/test_wsgi_ns.py | import cherrypy
from cherrypy.test import helper
class WSGI_Namespace_Test(helper.CPWebCase):
def setup_server():
class WSGIResponse(object):
def __init__(self, appresults):
self.appresults = appresults
self.iter = iter(appresults)
def __iter__(self):
return self
def next(self):
return self.iter.next()
def close(self):
if hasattr(self.appresults, "close"):
self.appresults.close()
class ChangeCase(object):
def __init__(self, app, to=None):
self.app = app
self.to = to
def __call__(self, environ, start_response):
res = self.app(environ, start_response)
class CaseResults(WSGIResponse):
def next(this):
return getattr(this.iter.next(), self.to)()
return CaseResults(res)
class Replacer(object):
def __init__(self, app, map={}):
self.app = app
self.map = map
def __call__(self, environ, start_response):
res = self.app(environ, start_response)
class ReplaceResults(WSGIResponse):
def next(this):
line = this.iter.next()
for k, v in self.map.iteritems():
line = line.replace(k, v)
return line
return ReplaceResults(res)
class Root(object):
def index(self):
return "HellO WoRlD!"
index.exposed = True
root_conf = {'wsgi.pipeline': [('replace', Replacer)],
'wsgi.replace.map': {'L': 'X', 'l': 'r'},
}
app = cherrypy.Application(Root())
app.wsgiapp.pipeline.append(('changecase', ChangeCase))
app.wsgiapp.config['changecase'] = {'to': 'upper'}
cherrypy.tree.mount(app, config={'/': root_conf})
setup_server = staticmethod(setup_server)
def test_pipeline(self):
if not cherrypy.server.httpserver:
return self.skip()
self.getPage("/")
# If body is "HEXXO WORXD!", the middleware was applied out of order.
self.assertBody("HERRO WORRD!")
| 2,570 | Python | .wsgi | 56 | 28.142857 | 77 | 0.512142 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,290 | test_wsgi_vhost.py | evilhero_mylar/lib/cherrypy/test/test_wsgi_vhost.py | import cherrypy
from cherrypy.test import helper
class WSGI_VirtualHost_Test(helper.CPWebCase):
def setup_server():
class ClassOfRoot(object):
def __init__(self, name):
self.name = name
def index(self):
return "Welcome to the %s website!" % self.name
index.exposed = True
default = cherrypy.Application(None)
domains = {}
for year in range(1997, 2008):
app = cherrypy.Application(ClassOfRoot('Class of %s' % year))
domains['www.classof%s.example' % year] = app
cherrypy.tree.graft(cherrypy._cpwsgi.VirtualHost(default, domains))
setup_server = staticmethod(setup_server)
def test_welcome(self):
if not cherrypy.server.using_wsgi:
return self.skip("skipped (not using WSGI)... ")
for year in range(1997, 2008):
self.getPage("/", headers=[('Host', 'www.classof%s.example' % year)])
self.assertBody("Welcome to the Class of %s website!" % year)
| 1,127 | Python | .wsgi | 23 | 35.608696 | 81 | 0.612808 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,291 | test_wsgiapps.py | evilhero_mylar/lib/cherrypy/test/test_wsgiapps.py | from cherrypy.test import helper
class WSGIGraftTests(helper.CPWebCase):
def setup_server():
import os
curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import cherrypy
def test_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
output = ['Hello, world!\n',
'This is a wsgi app running within CherryPy!\n\n']
keys = list(environ.keys())
keys.sort()
for k in keys:
output.append('%s: %s\n' % (k,environ[k]))
return output
def test_empty_string_app(environ, start_response):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return ['Hello', '', ' ', '', 'world']
class WSGIResponse(object):
def __init__(self, appresults):
self.appresults = appresults
self.iter = iter(appresults)
def __iter__(self):
return self
def next(self):
return self.iter.next()
def close(self):
if hasattr(self.appresults, "close"):
self.appresults.close()
class ReversingMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
results = app(environ, start_response)
class Reverser(WSGIResponse):
def next(this):
line = list(this.iter.next())
line.reverse()
return "".join(line)
return Reverser(results)
class Root:
def index(self):
return "I'm a regular CherryPy page handler!"
index.exposed = True
cherrypy.tree.mount(Root())
cherrypy.tree.graft(test_app, '/hosted/app1')
cherrypy.tree.graft(test_empty_string_app, '/hosted/app3')
# Set script_name explicitly to None to signal CP that it should
# be pulled from the WSGI environ each time.
app = cherrypy.Application(Root(), script_name=None)
cherrypy.tree.graft(ReversingMiddleware(app), '/hosted/app2')
setup_server = staticmethod(setup_server)
wsgi_output = '''Hello, world!
This is a wsgi app running within CherryPy!'''
def test_01_standard_app(self):
self.getPage("/")
self.assertBody("I'm a regular CherryPy page handler!")
def test_04_pure_wsgi(self):
import cherrypy
if not cherrypy.server.using_wsgi:
return self.skip("skipped (not using WSGI)... ")
self.getPage("/hosted/app1")
self.assertHeader("Content-Type", "text/plain")
self.assertInBody(self.wsgi_output)
def test_05_wrapped_cp_app(self):
import cherrypy
if not cherrypy.server.using_wsgi:
return self.skip("skipped (not using WSGI)... ")
self.getPage("/hosted/app2/")
body = list("I'm a regular CherryPy page handler!")
body.reverse()
body = "".join(body)
self.assertInBody(body)
def test_06_empty_string_app(self):
import cherrypy
if not cherrypy.server.using_wsgi:
return self.skip("skipped (not using WSGI)... ")
self.getPage("/hosted/app3")
self.assertHeader("Content-Type", "text/plain")
self.assertInBody('Hello world')
| 3,819 | Python | .wsgi | 84 | 31.547619 | 72 | 0.568722 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,292 | modwsgi.py | evilhero_mylar/lib/cherrypy/test/modwsgi.py | """Wrapper for mod_wsgi, for use as a CherryPy HTTP server.
To autostart modwsgi, the "apache" executable or script must be
on your system path, or you must override the global APACHE_PATH.
On some platforms, "apache" may be called "apachectl" or "apache2ctl"--
create a symlink to them if needed.
KNOWN BUGS
==========
##1. Apache processes Range headers automatically; CherryPy's truncated
## output is then truncated again by Apache. See test_core.testRanges.
## This was worked around in http://www.cherrypy.org/changeset/1319.
2. Apache does not allow custom HTTP methods like CONNECT as per the spec.
See test_core.testHTTPMethods.
3. Max request header and body settings do not work with Apache.
##4. Apache replaces status "reason phrases" automatically. For example,
## CherryPy may set "304 Not modified" but Apache will write out
## "304 Not Modified" (capital "M").
##5. Apache does not allow custom error codes as per the spec.
##6. Apache (or perhaps modpython, or modpython_gateway) unquotes %xx in the
## Request-URI too early.
7. mod_wsgi will not read request bodies which use the "chunked"
transfer-coding (it passes REQUEST_CHUNKED_ERROR to ap_setup_client_block
instead of REQUEST_CHUNKED_DECHUNK, see Apache2's http_protocol.c and
mod_python's requestobject.c).
8. When responding with 204 No Content, mod_wsgi adds a Content-Length
header for you.
9. When an error is raised, mod_wsgi has no facility for printing a
traceback as the response content (it's sent to the Apache log instead).
10. Startup and shutdown of Apache when running mod_wsgi seems slow.
"""
import os
curdir = os.path.abspath(os.path.dirname(__file__))
import re
import sys
import time
import cherrypy
from cherrypy.test import helper, webtest
def read_process(cmd, args=""):
pipein, pipeout = os.popen4("%s %s" % (cmd, args))
try:
firstline = pipeout.readline()
if (re.search(r"(not recognized|No such file|not found)", firstline,
re.IGNORECASE)):
raise IOError('%s must be on your system path.' % cmd)
output = firstline + pipeout.read()
finally:
pipeout.close()
return output
if sys.platform == 'win32':
APACHE_PATH = "httpd"
else:
APACHE_PATH = "apache"
CONF_PATH = "test_mw.conf"
conf_modwsgi = r"""
# Apache2 server conf file for testing CherryPy with modpython_gateway.
ServerName 127.0.0.1
DocumentRoot "/"
Listen %(port)s
AllowEncodedSlashes On
LoadModule rewrite_module modules/mod_rewrite.so
RewriteEngine on
RewriteMap escaping int:escape
LoadModule log_config_module modules/mod_log_config.so
LogFormat "%%h %%l %%u %%t \"%%r\" %%>s %%b \"%%{Referer}i\" \"%%{User-agent}i\"" combined
CustomLog "%(curdir)s/apache.access.log" combined
ErrorLog "%(curdir)s/apache.error.log"
LogLevel debug
LoadModule wsgi_module modules/mod_wsgi.so
LoadModule env_module modules/mod_env.so
WSGIScriptAlias / "%(curdir)s/modwsgi.py"
SetEnv testmod %(testmod)s
"""
class ModWSGISupervisor(helper.Supervisor):
"""Server Controller for ModWSGI and CherryPy."""
using_apache = True
using_wsgi = True
template=conf_modwsgi
def __str__(self):
return "ModWSGI Server on %s:%s" % (self.host, self.port)
def start(self, modulename):
mpconf = CONF_PATH
if not os.path.isabs(mpconf):
mpconf = os.path.join(curdir, mpconf)
f = open(mpconf, 'wb')
try:
output = (self.template %
{'port': self.port, 'testmod': modulename,
'curdir': curdir})
f.write(output)
finally:
f.close()
result = read_process(APACHE_PATH, "-k start -f %s" % mpconf)
if result:
print(result)
# Make a request so mod_wsgi starts up our app.
# If we don't, concurrent initial requests will 404.
cherrypy._cpserver.wait_for_occupied_port("127.0.0.1", self.port)
webtest.openURL('/ihopetheresnodefault', port=self.port)
time.sleep(1)
def stop(self):
"""Gracefully shutdown a server that is serving forever."""
read_process(APACHE_PATH, "-k stop")
loaded = False
def application(environ, start_response):
import cherrypy
global loaded
if not loaded:
loaded = True
modname = "cherrypy.test." + environ['testmod']
mod = __import__(modname, globals(), locals(), [''])
mod.setup_server()
cherrypy.config.update({
"log.error_file": os.path.join(curdir, "test.error.log"),
"log.access_file": os.path.join(curdir, "test.access.log"),
"environment": "test_suite",
"engine.SIGHUP": None,
"engine.SIGTERM": None,
})
return cherrypy.tree(environ, start_response)
| 4,880 | Python | .wsgi | 118 | 35.5 | 90 | 0.680401 | evilhero/mylar | 977 | 173 | 0 | GPL-3.0 | 9/5/2024, 5:12:46 PM (Europe/Amsterdam) |
21,293 | setup.py | pymupdf_PyMuPDF/setup.py | #! /usr/bin/env python3
'''
Overview:
Build script for PyMuPDF, supporting PEP-517 and simple command-line usage.
We hard-code the URL of the MuPDF .tar.gz file that we require. This
generally points to a particular source release on mupdf.com.
Default behaviour:
Building an sdist:
As of 2024-002-28 we no longer download the MuPDF .tar.gz file and
embed it within the sdist. Instead it will be downloaded at build
time.
Building PyMuPDF:
We first download the hard-coded mupdf .tar.gz file.
Then we extract and build MuPDF locally, before building PyMuPDF
itself. So PyMuPDF will always be built with the exact MuPDF
release that we require.
Environmental variables:
If building with system MuPDF (PYMUPDF_SETUP_MUPDF_BUILD is empty string):
CFLAGS
CXXFLAGS
LDFLAGS
Added to c, c++, and link commands.
PYMUPDF_INCLUDES
Colon-separated extra include paths.
PYMUPDF_MUPDF_LIB
Directory containing MuPDF libraries, (libmupdf.so,
libmupdfcpp.so).
PYMUPDF_SETUP_DEVENV
Location of devenv.com on Windows. If unset we search for it - see
wdev.py. if that fails we use just 'devenv.com'.
PYMUPDF_SETUP_FLAVOUR
Control building of separate wheels for PyMuPDF.
Must be unset or a combination of 'p', 'b' and 'd'.
Default is 'pbd'.
'p':
Generated wheel contains PyMuPDF code.
'b':
Generated wheel contains MuPDF libraries; these are independent of
the Python version.
'd':
Generated wheel contains includes and libraries for MuPDF.
If 'p' is included, the generated wheel is called PyMuPDF.
Otherwise if 'b' is included the generated wheel is called PyMuPDFb.
Otherwise if 'd' is included the generated wheel is called PyMuPDFd.
For example:
'pb': a `PyMuPDF` wheel with PyMuPDF runtime files and MuPDF
runtime shared libraries.
'b': a `PyMuPDFb` wheel containing MuPDF runtime shared libraries.
'pbd' a `PyMuPDF` wheel with PyMuPDF runtime files and MuPDF
runtime shared libraries, plus MuPDF build-time files (includes,
*.lib files on Windows).
'd': a `PyMuPDFd` wheel containing MuPDF build-time files
(includes, *.lib files on Windows).
PYMUPDF_SETUP_LIBCLANG
For internal testing.
PYMUPDF_SETUP_MUPDF_BUILD
If unset or '-', use internal hard-coded default MuPDF location.
Otherwise overrides location of MuPDF when building PyMuPDF:
Empty string:
Build PyMuPDF with the system MuPDF.
A string starting with 'git:':
Use `git clone` to get a MuPDF checkout. We use the
string in the git clone command; it must contain the git
URL from which to clone, and can also contain other `git
clone` args, for example:
PYMUPDF_SETUP_MUPDF_BUILD="git:--branch master https://github.com/ArtifexSoftware/mupdf.git"
Otherwise:
Location of mupdf directory.
PYMUPDF_SETUP_MUPDF_BSYMBOLIC
If '0' we do not link libmupdf.so with -Bsymbolic.
PYMUPDF_SETUP_MUPDF_TESSERACT
If '0' we build MuPDF without Tesseract.
PYMUPDF_SETUP_MUPDF_BUILD_TYPE
Unix only. Controls build type of MuPDF. Supported values are:
debug
memento
release (default)
PYMUPDF_SETUP_MUPDF_CLEAN
Unix only. If '1', we do a clean MuPDF build.
PYMUPDF_SETUP_MUPDF_REFCHECK_IF
Should be preprocessor statement to enable MuPDF reference count
checking.
As of 2024-09-27, MuPDF default is `#ifndef NDEBUG`.
PYMUPDF_SETUP_MUPDF_TRACE_IF
Should be preprocessor statement to enable MuPDF runtime diagnostics in
response to environment variables such as MUPDF_trace.
As of 2024-09-27, MuPDF default is `#ifndef NDEBUG`.
PYMUPDF_SETUP_MUPDF_THIRD
If '0' and we are building on Linux with the system MuPDF
(i.e. PYMUPDF_SETUP_MUPDF_BUILD=''), then don't link with
`-lmupdf-third`.
PYMUPDF_SETUP_MUPDF_VS_UPGRADE
If '1' we run mupdf `scripts/mupdfwrap.py` with `--vs-upgrade 1` to
help Windows builds work with Visual Studio versions newer than 2019.
PYMUPDF_SETUP_MUPDF_TGZ
If set, overrides location of MuPDF .tar.gz file:
Empty string:
Do not download MuPDF .tar.gz file. Sdist's will not contain
MuPDF.
A string containing '://':
The URL from which to download the MuPDF .tar.gz file. Leaf
must match mupdf-*.tar.gz.
Otherwise:
The path of local mupdf git checkout. We put all files in this
checkout known to git into a local tar archive.
PYMUPDF_SETUP_MUPDF_OVERWRITE_CONFIG
If '0' we do not overwrite MuPDF's include/mupdf/fitz/config.h with
PyMuPDF's own configuration file, before building MuPDF.
PYMUPDF_SETUP_MUPDF_REBUILD
If 0 we do not (re)build mupdf.
PYMUPDF_SETUP_PY_LIMITED_API
If not '0', we build for current Python's stable ABI.
PYMUPDF_SETUP_URL_WHEEL
If set, we use an existing wheel instead of building a new wheel.
If starts with `http://` or `https://`:
If ends with '/', we append our wheel name and download. Otherwise
we download directly.
If starts with `file://`:
If ends with '/' we look for a matching wheel name, `using
pipcl.wheel_name_match()` to cope with differing platform tags,
for example our `manylinux2014_x86_64` will match with an existing
wheel with `manylinux2014_x86_64.manylinux_2_17_x86_64`.
Any other prefix is an error.
WDEV_VS_YEAR
If set, we use as Visual Studio year, for example '2019' or '2022'.
WDEV_VS_GRADE
If set, we use as Visual Studio grade, for example 'Community' or
'Professional' or 'Enterprise'.
'''
import glob
import io
import os
import textwrap
import time
import platform
import re
import shlex
import shutil
import stat
import subprocess
import sys
import tarfile
import urllib.request
import zipfile
import pipcl
_log_prefix = None
def log( text):
global _log_prefix
if not _log_prefix:
# This typically sets _log_prefix to `PyMuPDF/setup.py`.
p = os.path.abspath( __file__)
p, p1 = os.path.split( p)
p, p0 = os.path.split( p)
_log_prefix = os.path.join( p0, p1)
print(f'{_log_prefix}: {text}', file=sys.stdout)
sys.stdout.flush()
if 1:
# For debugging.
log(f'### Starting.')
log(f'__name__: {__name__!r}')
log(f'platform.platform(): {platform.platform()!r}')
log(f'platform.python_version(): {platform.python_version()!r}')
log(f'sys.executable: {sys.executable!r}')
log(f'CPU bits: {32 if sys.maxsize == 2**31 - 1 else 64} {sys.maxsize=}')
log(f'__file__: {__file__!r}')
log(f'os.getcwd(): {os.getcwd()!r}')
log(f'sys.argv ({len(sys.argv)}):')
for i, arg in enumerate(sys.argv):
log(f' {i}: {arg!r}')
log(f'os.environ ({len(os.environ)}):')
for k in sorted( os.environ.keys()):
v = os.environ[ k]
log( f' {k}: {v!r}')
PYMUPDF_SETUP_FLAVOUR = os.environ.get( 'PYMUPDF_SETUP_FLAVOUR', 'pbd')
for i in PYMUPDF_SETUP_FLAVOUR:
assert i in 'pbd', f'Unrecognised flag "{i} in {PYMUPDF_SETUP_FLAVOUR=}. Should be one of "p", "b", "d"'
g_root = os.path.abspath( f'{__file__}/..')
# Name of file that identifies that we are in a PyMuPDF sdist.
g_pymupdfb_sdist_marker = 'pymupdfb_sdist'
PYMUPDF_SETUP_PY_LIMITED_API = os.environ.get('PYMUPDF_SETUP_PY_LIMITED_API')
assert PYMUPDF_SETUP_PY_LIMITED_API in (None, '', '0', '1'), \
f'Should be "", "0", "1" or undefined: {PYMUPDF_SETUP_PY_LIMITED_API=}.'
g_py_limited_api = (PYMUPDF_SETUP_PY_LIMITED_API != '0')
PYMUPDF_SETUP_URL_WHEEL = os.environ.get('PYMUPDF_SETUP_URL_WHEEL')
log(f'{PYMUPDF_SETUP_URL_WHEEL=}')
def _fs_remove(path):
'''
Removes file or directory, without raising exception if it doesn't exist.
We assert-fail if the path still exists when we return, in case of
permission problems etc.
'''
# First try deleting `path` as a file.
try:
os.remove( path)
except Exception as e:
pass
if os.path.exists(path):
# Try deleting `path` as a directory. Need to use
# shutil.rmtree() callback to handle permission problems; see:
# https://docs.python.org/3/library/shutil.html#rmtree-example
#
def error_fn(fn, path, excinfo):
# Clear the readonly bit and reattempt the removal.
os.chmod(path, stat.S_IWRITE)
fn(path)
shutil.rmtree( path, onerror=error_fn)
assert not os.path.exists( path)
def run(command, check=1):
log(f'Running: {command}')
return subprocess.run( command, shell=1, check=check)
def _git_get_branch( directory):
command = f'cd {directory} && git branch --show-current'
log( f'Running: {command}')
p = subprocess.run(
command,
shell=True,
check=False,
text=True,
stdout=subprocess.PIPE,
)
ret = None
if p.returncode == 0:
ret = p.stdout.strip()
log( f'Have found MuPDF git branch: ret={ret!r}')
return ret
def tar_check(path, mode='r:gz', prefix=None, remove=False):
'''
Checks items in tar file have same <top-directory>, or <prefix> if not None.
We fail if items in tar file have different top-level directory names.
path:
The tar file.
mode:
As tarfile.open().
prefix:
If not None, we fail if tar file's <top-directory> is not <prefix>.
Returns the directory name (which will be <prefix> if not None).
'''
with tarfile.open( path, mode) as t:
items = t.getnames()
assert items
item = items[0]
assert not item.startswith('./') and not item.startswith('../')
s = item.find('/')
if s == -1:
prefix_actual = item + '/'
else:
prefix_actual = item[:s+1]
if prefix:
assert prefix == prefix_actual, f'{path=} {prefix=} {prefix_actual=}'
for item in items[1:]:
assert item.startswith( prefix_actual), f'prefix_actual={prefix_actual!r} != item={item!r}'
return prefix_actual
def tar_extract(path, mode='r:gz', prefix=None, exists='raise'):
'''
Extracts tar file into single local directory.
We fail if items in tar file have different <top-directory>.
path:
The tar file.
mode:
As tarfile.open().
prefix:
If not None, we fail if tar file's <top-directory> is not <prefix>.
exists:
What to do if <top-directory> already exists:
'raise': raise exception.
'remove': remove existing file/directory before extracting.
'return': return without extracting.
Returns the directory name (which will be <prefix> if not None, with '/'
appended if not already present).
'''
prefix_actual = tar_check( path, mode, prefix)
if os.path.exists( prefix_actual):
if exists == 'raise':
raise Exception( f'Path already exists: {prefix_actual!r}')
elif exists == 'remove':
remove( prefix_actual)
elif exists == 'return':
log( f'Not extracting {path} because already exists: {prefix_actual}')
return prefix_actual
else:
assert 0, f'Unrecognised exists={exists!r}'
assert not os.path.exists( prefix_actual), f'Path already exists: {prefix_actual}'
log( f'Extracting {path}')
with tarfile.open( path, mode) as t:
t.extractall()
return prefix_actual
def get_git_id( directory):
'''
Returns `(sha, comment, diff, branch)`, all items are str or None if not
available.
directory:
Root of git checkout.
'''
sha, comment, diff, branch = '', '', '', ''
cp = subprocess.run(
f'cd {directory} && (PAGER= git show --pretty=oneline|head -n 1 && git diff)',
capture_output=1,
shell=1,
text=1,
)
if cp.returncode == 0:
sha, _ = cp.stdout.split(' ', 1)
comment, diff = _.split('\n', 1)
cp = subprocess.run(
f'cd {directory} && git rev-parse --abbrev-ref HEAD',
capture_output=1,
shell=1,
text=1,
)
if cp.returncode == 0:
branch = cp.stdout.strip()
log(f'get_git_id(): directory={directory!r} returning branch={branch!r} sha={sha!r} comment={comment!r}')
return sha, comment, diff, branch
mupdf_tgz = os.path.abspath( f'{__file__}/../mupdf.tgz')
def get_mupdf_internal(out, location=None, sha=None, local_tgz=None):
'''
Gets MuPDF as either a .tgz or a local directory.
Args:
out:
Either 'dir' (we return name of local directory containing mupdf) or 'tgz' (we return
name of local .tgz file containing mupdf).
location:
First, if None we set to hard-coded default URL or git location.
If starts with 'git:', should be remote git location.
Otherwise if containing '://' should be URL for .tgz.
Otherwise should path of local mupdf checkout.
sha:
If not None and we use git clone, we checkout this sha.
local_tgz:
If not None, must be local .tgz file.
Returns:
(path, location):
`path` is absolute path of local directory or .tgz containing
MuPDF, or None if we are to use system MuPDF.
`location_out` is `location` if not None, else the hard-coded
default location.
'''
log(f'get_mupdf_internal(): {out=} {location=} {sha=}')
assert out in ('dir', 'tgz')
if location is None:
location = 'https://mupdf.com/downloads/archive/mupdf-1.24.10-source.tar.gz'
#location = 'git:--branch master https://github.com/ArtifexSoftware/mupdf.git'
if location == '':
# Use system mupdf.
return None, location
local_dir = None
if local_tgz:
assert os.path.isfile(local_tgz)
elif location.startswith( 'git:'):
location_git = location[4:]
local_dir = 'mupdf-git'
# Try to update existing checkout.
e = run(f'cd {local_dir} && git pull && git submodule update --init', check=False).returncode
if e:
# No existing git checkout, so do a fresh clone.
_fs_remove(local_dir)
run(f'git clone --recursive --depth 1 --shallow-submodules {location[4:]} {local_dir}')
# Show sha of checkout.
run( f'cd {local_dir} && git show --pretty=oneline|head -n 1', check=False)
if sha:
run( f'cd {local_dir} && git checkout {sha}')
elif '://' in location:
# Download .tgz.
local_tgz = os.path.basename( location)
suffix = '.tar.gz'
assert location.endswith(suffix), f'Unrecognised suffix in remote URL {location=}.'
name = local_tgz[:-len(suffix)]
log( f'Download {location=} {local_tgz=} {name=}')
if os.path.exists(local_tgz):
try:
tar_check(local_tgz, 'r:gz', prefix=f'{name}/')
except Exception as e:
log(f'Not using existing file {local_tgz} because invalid tar data: {e}')
_fs_remove( local_tgz)
if os.path.exists(local_tgz):
log(f'Not downloading from {location} because already present: {local_tgz!r}')
else:
log(f'Downloading from {location=} to {local_tgz=}.')
urllib.request.urlretrieve( location, local_tgz + '-')
os.rename(local_tgz + '-', local_tgz)
assert os.path.exists( local_tgz)
tar_check( local_tgz, 'r:gz', prefix=f'{name}/')
else:
assert os.path.isdir(location), f'Local MuPDF does not exist: {location=}'
local_dir = location
assert bool(local_dir) != bool(local_tgz)
if out == 'dir':
if not local_dir:
assert local_tgz
local_dir = tar_extract( local_tgz, exists='return')
return os.path.abspath( local_dir), location
elif out == 'tgz':
if not local_tgz:
# Create .tgz containing git files in `local_dir`.
assert local_dir
if local_dir.endswith( '/'):
local_dir = local_dir[:-1]
top = os.path.basename(local_dir)
local_tgz = f'{local_dir}.tgz'
log( f'Creating .tgz from git files. {top=} {local_dir=} {local_tgz=}')
_fs_remove( local_tgz)
with tarfile.open( local_tgz, 'w:gz') as f:
for name in pipcl.git_items( local_dir, submodules=True):
path = os.path.join( local_dir, name)
if os.path.isfile( path):
path2 = f'{top}/{name}'
log(f'Adding {path=} {path2=}.')
f.add( path, path2, recursive=False)
return os.path.abspath( local_tgz), location
else:
assert 0, f'Unrecognised {out=}'
def get_mupdf_tgz():
'''
Creates .tgz file called containing MuPDF source, for inclusion in an
sdist.
What we do depends on environmental variable PYMUPDF_SETUP_MUPDF_TGZ; see
docs at start of this file for details.
Returns name of top-level directory within the .tgz file.
'''
name, location = get_mupdf_internal( 'tgz', os.environ.get('PYMUPDF_SETUP_MUPDF_TGZ'))
return name, location
def get_mupdf(path=None, sha=None):
'''
Downloads and/or extracts mupdf and returns (path, location) where `path`
is the local mupdf directory and `location` is where it came from.
Exact behaviour depends on environmental variable
PYMUPDF_SETUP_MUPDF_BUILD; see docs at start of this file for details.
'''
m = os.environ.get('PYMUPDF_SETUP_MUPDF_BUILD')
if m == '-':
# This allows easy specification in Github actions.
m = None
if m is None and os.path.isfile(mupdf_tgz):
# This makes us use tgz inside sdist.
log(f'Using local tgz: {mupdf_tgz=}')
return get_mupdf_internal('dir', local_tgz=mupdf_tgz)
return get_mupdf_internal('dir', m)
linux = sys.platform.startswith( 'linux') or 'gnu' in sys.platform
openbsd = sys.platform.startswith( 'openbsd')
freebsd = sys.platform.startswith( 'freebsd')
darwin = sys.platform.startswith( 'darwin')
windows = platform.system() == 'Windows' or platform.system().startswith('CYGWIN')
msys2 = platform.system().startswith('MSYS_NT-')
pyodide = os.environ.get('OS') == 'pyodide'
def build():
'''
pipcl.py `build_fn()` callback.
'''
# Download MuPDF.
#
mupdf_local, mupdf_location = get_mupdf()
build_type = os.environ.get( 'PYMUPDF_SETUP_MUPDF_BUILD_TYPE', 'release')
assert build_type in ('debug', 'memento', 'release'), \
f'Unrecognised build_type={build_type!r}'
overwrite_config = os.environ.get('PYMUPDF_SETUP_MUPDF_OVERWRITE_CONFIG', '1') == '1'
PYMUPDF_SETUP_MUPDF_REFCHECK_IF = os.environ.get('PYMUPDF_SETUP_MUPDF_REFCHECK_IF')
PYMUPDF_SETUP_MUPDF_TRACE_IF = os.environ.get('PYMUPDF_SETUP_MUPDF_TRACE_IF')
# Build MuPDF shared libraries.
#
if windows:
mupdf_build_dir = build_mupdf_windows(
mupdf_local,
build_type,
overwrite_config,
g_py_limited_api,
PYMUPDF_SETUP_MUPDF_REFCHECK_IF,
PYMUPDF_SETUP_MUPDF_TRACE_IF,
)
else:
if 'p' not in PYMUPDF_SETUP_FLAVOUR and 'b' not in PYMUPDF_SETUP_FLAVOUR:
# We only need MuPDF headers, so no point building MuPDF.
log(f'Not building MuPDF because not Windows and {PYMUPDF_SETUP_FLAVOUR=}.')
mupdf_build_dir = None
else:
mupdf_build_dir = build_mupdf_unix(
mupdf_local,
build_type,
overwrite_config,
g_py_limited_api,
PYMUPDF_SETUP_MUPDF_REFCHECK_IF,
PYMUPDF_SETUP_MUPDF_TRACE_IF,
)
log( f'build(): mupdf_build_dir={mupdf_build_dir!r}')
# Build rebased `extra` module.
#
if 'p' in PYMUPDF_SETUP_FLAVOUR:
path_so_leaf = _build_extension(
mupdf_local,
mupdf_build_dir,
build_type,
g_py_limited_api,
)
else:
log(f'Not building extension.')
path_so_leaf = None
# Generate list of (from, to) items to return to pipcl. What we add depends
# on PYMUPDF_SETUP_FLAVOUR.
#
ret = list()
def add(flavour, from_, to_):
assert flavour in 'pbd'
if flavour in PYMUPDF_SETUP_FLAVOUR:
ret.append((from_, to_))
to_dir = 'pymupdf/'
to_dir_d = f'{to_dir}/mupdf-devel'
# Add implementation files.
add('p', f'{g_root}/src/__init__.py', to_dir)
add('p', f'{g_root}/src/__main__.py', to_dir)
add('p', f'{g_root}/src/pymupdf.py', to_dir)
add('p', f'{g_root}/src/table.py', to_dir)
add('p', f'{g_root}/src/utils.py', to_dir)
add('p', f'{g_root}/src/_apply_pages.py', to_dir)
add('p', f'{g_root}/src/build/extra.py', to_dir)
if path_so_leaf:
add('p', f'{g_root}/src/build/{path_so_leaf}', to_dir)
# Add support for `fitz` backwards compatibility.
add('p', f'{g_root}/src/fitz___init__.py', 'fitz/__init__.py')
add('p', f'{g_root}/src/fitz_table.py', 'fitz/table.py')
add('p', f'{g_root}/src/fitz_utils.py', 'fitz/utils.py')
if mupdf_local:
# Add MuPDF Python API.
add('p', f'{mupdf_build_dir}/mupdf.py', to_dir)
# Add MuPDF shared libraries.
if windows:
wp = pipcl.wdev.WindowsPython()
add('p', f'{mupdf_build_dir}/_mupdf.pyd', to_dir)
add('b', f'{mupdf_build_dir}/mupdfcpp{wp.cpu.windows_suffix}.dll', to_dir)
# Add Windows .lib files.
mupdf_build_dir2 = _windows_lib_directory(mupdf_local, build_type)
add('d', f'{mupdf_build_dir2}/mupdfcpp{wp.cpu.windows_suffix}.lib', f'{to_dir_d}/lib/')
elif darwin:
add('p', f'{mupdf_build_dir}/_mupdf.so', to_dir)
add('b', f'{mupdf_build_dir}/libmupdfcpp.so', to_dir)
add('b', f'{mupdf_build_dir}/libmupdf.dylib', f'{to_dir}libmupdf.dylib')
elif pyodide:
add('p', f'{mupdf_build_dir}/_mupdf.so', to_dir)
add('b', f'{mupdf_build_dir}/libmupdfcpp.so', 'PyMuPDF.libs/')
add('b', f'{mupdf_build_dir}/libmupdf.so', 'PyMuPDF.libs/')
else:
add('p', f'{mupdf_build_dir}/_mupdf.so', to_dir)
add('b', pipcl.get_soname(f'{mupdf_build_dir}/libmupdfcpp.so'), to_dir)
add('b', pipcl.get_soname(f'{mupdf_build_dir}/libmupdf.so'), to_dir)
if 'd' in PYMUPDF_SETUP_FLAVOUR:
# Add MuPDF headers to `ret_d`. Would prefer to use
# pipcl.git_items() but hard-coded mupdf tree is not a git
# checkout.
#
include = f'{mupdf_local}/include'
for dirpath, dirnames, filenames in os.walk(include):
for filename in filenames:
header_abs = os.path.join(dirpath, filename)
assert header_abs.startswith(include)
header_rel = header_abs[len(include)+1:]
add('d', f'{header_abs}', f'{to_dir_d}/include/{header_rel}')
# Add a .py file containing location of MuPDF.
text = f"mupdf_location='{mupdf_location}'\n"
add('p', text.encode(), f'{to_dir}/_build.py')
# Add single README file.
if 'p' in PYMUPDF_SETUP_FLAVOUR:
add('p', f'{g_root}/README.md', '$dist-info/README.md')
elif 'b' in PYMUPDF_SETUP_FLAVOUR:
add('b', f'{g_root}/READMEb.md', '$dist-info/README.md')
elif 'd' in PYMUPDF_SETUP_FLAVOUR:
add('d', f'{g_root}/READMEd.md', '$dist-info/README.md')
return ret
def env_add(env, name, value, sep=' ', prepend=False, verbose=False):
'''
Appends/prepends `<value>` to `env[name]`.
If `name` is not in `env`, we use os.environ[name] if it exists.
'''
v = env.get(name)
if verbose:
log(f'Initally: {name}={v!r}')
if v is None:
v = os.environ.get(name)
if v is None:
env[ name] = value
else:
if prepend:
env[ name] = f'{value}{sep}{v}'
else:
env[ name] = f'{v}{sep}{value}'
if verbose:
log(f'Returning with {name}={env[name]!r}')
def build_mupdf_windows(
mupdf_local,
build_type,
overwrite_config,
g_py_limited_api,
PYMUPDF_SETUP_MUPDF_REFCHECK_IF,
PYMUPDF_SETUP_MUPDF_TRACE_IF,
):
assert mupdf_local
if overwrite_config:
mupdf_config_h = f'{mupdf_local}/include/mupdf/fitz/config.h'
prefix = '#define TOFU_CJK_EXT 1 /* PyMuPDF override. */\n'
with open(mupdf_config_h) as f:
text = f.read()
if text.startswith(prefix):
print(f'Not modifying {mupdf_config_h} because already has prefix {prefix!r}.')
else:
print(f'Prefixing {mupdf_config_h} with {prefix!r}.')
text = prefix + text
st = os.stat(mupdf_config_h)
with open(mupdf_config_h, 'w') as f:
f.write(text)
os.utime(mupdf_config_h, (st.st_atime, st.st_mtime))
wp = pipcl.wdev.WindowsPython()
tesseract = '' if os.environ.get('PYMUPDF_SETUP_MUPDF_TESSERACT') == '0' else 'tesseract-'
windows_build_tail = f'build\\shared-{tesseract}{build_type}'
if g_py_limited_api:
windows_build_tail += f'-Py_LIMITED_API={pipcl.current_py_limited_api()}'
windows_build_tail += f'-x{wp.cpu.bits}-py{wp.version}'
windows_build_dir = f'{mupdf_local}\\{windows_build_tail}'
#log( f'Building mupdf.')
devenv = os.environ.get('PYMUPDF_SETUP_DEVENV')
if not devenv:
vs = pipcl.wdev.WindowsVS()
devenv = vs.devenv
if not devenv:
devenv = 'devenv.com'
log( f'Cannot find devenv.com in default locations, using: {devenv!r}')
command = f'cd "{mupdf_local}" && "{sys.executable}" ./scripts/mupdfwrap.py'
if os.environ.get('PYMUPDF_SETUP_MUPDF_VS_UPGRADE') == '1':
command += ' --vs-upgrade 1'
# Would like to simply do f'... --devenv {shutil.quote(devenv)}', but
# it looks like if `devenv` has spaces then `shutil.quote()` puts it
# inside single quotes, which then appear to be ignored when run by
# subprocess.run().
#
# So instead we strip any enclosing quotes and the enclose with
# double-quotes.
#
if len(devenv) >= 2:
for q in '"', "'":
if devenv.startswith( q) and devenv.endswith( q):
devenv = devenv[1:-1]
command += f' -d {windows_build_tail}'
command += f' -b'
if PYMUPDF_SETUP_MUPDF_REFCHECK_IF:
command += f' --refcheck-if "{PYMUPDF_SETUP_MUPDF_REFCHECK_IF}"'
if PYMUPDF_SETUP_MUPDF_TRACE_IF:
command += f' --trace-if "{PYMUPDF_SETUP_MUPDF_TRACE_IF}"'
command += f' --devenv "{devenv}"'
command += f' all'
if os.environ.get( 'PYMUPDF_SETUP_MUPDF_REBUILD') == '0':
log( f'PYMUPDF_SETUP_MUPDF_REBUILD is "0" so not building MuPDF; would have run: {command}')
else:
log( f'Building MuPDF by running: {command}')
subprocess.run( command, shell=True, check=True)
log( f'Finished building mupdf.')
return windows_build_dir
def _windows_lib_directory(mupdf_local, build_type):
ret = f'{mupdf_local}/platform/win32/'
if _cpu_bits() == 64:
ret += 'x64/'
if build_type == 'release':
ret += 'Release/'
elif build_type == 'debug':
ret += 'Debug/'
else:
assert 0, f'Unrecognised {build_type=}.'
return ret
def _cpu_bits():
if sys.maxsize == 2**31 - 1:
return 32
return 64
def build_mupdf_unix(
mupdf_local,
build_type,
overwrite_config,
g_py_limited_api,
PYMUPDF_SETUP_MUPDF_REFCHECK_IF,
PYMUPDF_SETUP_MUPDF_TRACE_IF,
):
'''
Builds MuPDF.
Args:
mupdf_local:
Path of MuPDF directory or None if we are using system MuPDF.
Returns the absolute path of build directory within MuPDF, e.g.
`.../mupdf/build/pymupdf-shared-release`, or `None` if we are using the
system MuPDF.
'''
if not mupdf_local:
log( f'Using system mupdf.')
return None
env = dict()
if overwrite_config:
# By predefining TOFU_CJK_EXT here, we don't need to modify
# MuPDF's include/mupdf/fitz/config.h.
log( f'Setting XCFLAGS and XCXXFLAGS to predefine TOFU_CJK_EXT.')
env_add(env, 'XCFLAGS', '-DTOFU_CJK_EXT')
env_add(env, 'XCXXFLAGS', '-DTOFU_CJK_EXT')
if openbsd or freebsd:
env_add(env, 'CXX', 'c++', ' ')
# Add extra flags for MacOS cross-compilation, where ARCHFLAGS can be
# '-arch arm64'.
#
archflags = os.environ.get( 'ARCHFLAGS')
if archflags:
env_add(env, 'XCFLAGS', archflags)
env_add(env, 'XLIBS', archflags)
# We specify a build directory path containing 'pymupdf' so that we
# coexist with non-PyMuPDF builds (because PyMuPDF builds have a
# different config.h).
#
# We also append further text to try to allow different builds to
# work if they reuse the mupdf directory.
#
# Using platform.machine() (e.g. 'amd64') ensures that different
# builds of mupdf on a shared filesystem can coexist. Using
# $_PYTHON_HOST_PLATFORM allows cross-compiled cibuildwheel builds
# to coexist, e.g. on github.
#
build_prefix = f'PyMuPDF-'
if pyodide:
build_prefix += 'pyodide-'
else:
build_prefix += f'{platform.machine()}-'
build_prefix_extra = os.environ.get( '_PYTHON_HOST_PLATFORM')
if build_prefix_extra:
build_prefix += f'{build_prefix_extra}-'
build_prefix += 'shared-'
if msys2:
# Error in mupdf/scripts/tesseract/endianness.h:
# #error "I don't know what architecture this is!"
log(f'msys2: building MuPDF without tesseract.')
elif os.environ.get('PYMUPDF_SETUP_MUPDF_TESSERACT') == '0':
log(f'PYMUPDF_SETUP_MUPDF_TESSERACT=0 so building mupdf without tesseract.')
else:
build_prefix += 'tesseract-'
mupdf_version_tuple = get_mupdf_version(mupdf_local)
if (
linux
and os.environ.get('PYMUPDF_SETUP_MUPDF_BSYMBOLIC', '1') == '1'
and mupdf_version_tuple >= (1, 24, 3)
):
log(f'Appending `bsymbolic-` to MuPDF build path.')
build_prefix += 'bsymbolic-'
log(f'{g_py_limited_api=}')
if g_py_limited_api:
build_prefix += f'Py_LIMITED_API={pipcl.current_py_limited_api()}-'
unix_build_dir = f'{mupdf_local}/build/{build_prefix}{build_type}'
# We need MuPDF's Python bindings, so we build MuPDF with
# `mupdf/scripts/mupdfwrap.py` instead of running `make`.
#
command = f'cd {mupdf_local} &&'
for n, v in env.items():
command += f' {n}={shlex.quote(v)}'
command += f' {sys.executable} ./scripts/mupdfwrap.py -d build/{build_prefix}{build_type} -b'
#command += f' --m-target libs'
if PYMUPDF_SETUP_MUPDF_REFCHECK_IF:
command += f' --refcheck-if "{PYMUPDF_SETUP_MUPDF_REFCHECK_IF}"'
if PYMUPDF_SETUP_MUPDF_TRACE_IF:
command += f' --trace-if "{PYMUPDF_SETUP_MUPDF_TRACE_IF}"'
if 'p' in PYMUPDF_SETUP_FLAVOUR:
command += ' all'
else:
command += ' m01' # No need for C++/Python bindings.
command += f' && echo {unix_build_dir}:'
command += f' && ls -l {unix_build_dir}'
if os.environ.get( 'PYMUPDF_SETUP_MUPDF_REBUILD') == '0':
log( f'PYMUPDF_SETUP_MUPDF_REBUILD is "0" so not building MuPDF; would have run: {command}')
else:
log( f'Building MuPDF by running: {command}')
subprocess.run( command, shell=True, check=True)
log( f'Finished building mupdf.')
return unix_build_dir
def get_mupdf_version(mupdf_dir):
path = f'{mupdf_dir}/include/mupdf/fitz/version.h'
with open(path) as f:
text = f.read()
v0 = re.search('#define FZ_VERSION_MAJOR ([0-9]+)', text)
v1 = re.search('#define FZ_VERSION_MINOR ([0-9]+)', text)
v2 = re.search('#define FZ_VERSION_PATCH ([0-9]+)', text)
assert v0 and v1 and v2, f'Cannot find MuPDF version numbers in {path=}.'
v0 = int(v0.group(1))
v1 = int(v1.group(1))
v2 = int(v2.group(1))
return v0, v1, v2
def _fs_update(text, path):
try:
with open( path) as f:
text0 = f.read()
except OSError:
text0 = None
print(f'path={path!r} text==text0={text==text0!r}')
if text != text0:
with open( path, 'w') as f:
f.write( text)
def _build_extension( mupdf_local, mupdf_build_dir, build_type, g_py_limited_api):
'''
Builds Python extension module `_extra`.
Returns leafname of the generated shared libraries within mupdf_build_dir.
'''
(compiler_extra, linker_extra, includes, defines, optimise, debug, libpaths, libs, libraries) \
= _extension_flags( mupdf_local, mupdf_build_dir, build_type)
log(f'_build_extension(): {g_py_limited_api=} {defines=}')
if mupdf_local:
includes = (
f'{mupdf_local}/platform/c++/include',
f'{mupdf_local}/include',
)
# Build rebased extension module.
log('Building PyMuPDF rebased.')
compile_extra_cpp = ''
if darwin:
# Avoids `error: cannot pass object of non-POD type
# 'std::nullptr_t' through variadic function; call will abort at
# runtime` when compiling `mupdf::pdf_dict_getl(..., nullptr)`.
compile_extra_cpp += ' -Wno-non-pod-varargs'
# Avoid errors caused by mupdf's C++ bindings' exception classes
# not having `nothrow` to match the base exception class.
compile_extra_cpp += ' -std=c++14'
if windows:
wp = pipcl.wdev.WindowsPython()
libs = f'mupdfcpp{wp.cpu.windows_suffix}.lib'
else:
libs = ('mupdf', 'mupdfcpp')
libraries = [
f'{mupdf_build_dir}/libmupdf.so'
f'{mupdf_build_dir}/libmupdfcpp.so'
]
path_so_leaf = pipcl.build_extension(
name = 'extra',
path_i = f'{g_root}/src/extra.i',
outdir = f'{g_root}/src/build',
includes = includes,
defines = defines,
libpaths = libpaths,
libs = libs,
compiler_extra = compiler_extra + compile_extra_cpp,
linker_extra = linker_extra,
optimise = optimise,
debug = debug,
prerequisites_swig = None,
prerequisites_compile = f'{mupdf_local}/include',
prerequisites_link = libraries,
py_limited_api = g_py_limited_api,
)
return path_so_leaf
def _extension_flags( mupdf_local, mupdf_build_dir, build_type):
'''
Returns various flags to pass to pipcl.build_extension().
'''
compiler_extra = ''
linker_extra = ''
if build_type == 'memento':
compiler_extra += ' -DMEMENTO'
if mupdf_build_dir:
mupdf_build_dir_flags = os.path.basename( mupdf_build_dir).split( '-')
else:
mupdf_build_dir_flags = [build_type]
optimise = 'release' in mupdf_build_dir_flags
debug = 'debug' in mupdf_build_dir_flags
r_extra = ''
defines = list()
if windows:
defines.append('FZ_DLL_CLIENT')
wp = pipcl.wdev.WindowsPython()
if os.environ.get('PYMUPDF_SETUP_MUPDF_VS_UPGRADE') == '1':
# MuPDF C++ build uses a parallel build tree with updated VS files.
infix = 'win32-vs-upgrade'
else:
infix = 'win32'
build_type_infix = 'Debug' if debug else 'Release'
libpaths = (
f'{mupdf_local}\\platform\\{infix}\\{wp.cpu.windows_subdir}{build_type_infix}',
f'{mupdf_local}\\platform\\{infix}\\{wp.cpu.windows_subdir}{build_type_infix}Tesseract',
)
libs = f'mupdfcpp{wp.cpu.windows_suffix}.lib'
libraries = f'{mupdf_local}\\platform\\{infix}\\{wp.cpu.windows_subdir}{build_type_infix}\\{libs}'
compiler_extra = ''
else:
libs = ['mupdf']
compiler_extra += (
' -Wall'
' -Wno-deprecated-declarations'
' -Wno-unused-const-variable'
)
if mupdf_local:
libpaths = (mupdf_build_dir,)
libraries = f'{mupdf_build_dir}/{libs[0]}'
if openbsd:
compiler_extra += ' -Wno-deprecated-declarations'
else:
libpaths = os.environ.get('PYMUPDF_MUPDF_LIB')
libraries = None
if libpaths:
libpaths = libpaths.split(':')
if mupdf_local:
includes = (
f'{mupdf_local}/include',
f'{mupdf_local}/include/mupdf',
f'{mupdf_local}/thirdparty/freetype/include',
)
else:
# Use system MuPDF.
includes = list()
pi = os.environ.get('PYMUPDF_INCLUDES')
if pi:
includes += pi.split(':')
pmi = os.environ.get('PYMUPDF_MUPDF_INCLUDE')
if pmi:
includes.append(pmi)
ldflags = os.environ.get('LDFLAGS')
if ldflags:
linker_extra += f' {ldflags}'
cflags = os.environ.get('CFLAGS')
if cflags:
compiler_extra += f' {cflags}'
cxxflags = os.environ.get('CXXFLAGS')
if cxxflags:
compiler_extra += f' {cxxflags}'
return compiler_extra, linker_extra, includes, defines, optimise, debug, libpaths, libs, libraries,
def sdist():
ret = list()
if PYMUPDF_SETUP_FLAVOUR == 'b':
# Create a minimal sdist that will build/install a dummy PyMuPDFb.
for p in (
'setup.py',
'pipcl.py',
'wdev.py',
'pyproject.toml',
):
ret.append(p)
ret.append(
(
b'This file indicates that we are a PyMuPDFb sdist and should build/install a dummy PyMuPDFb package.\n',
g_pymupdfb_sdist_marker,
)
)
return ret
for p in pipcl.git_items( g_root):
if p.startswith(
(
'docs/',
'signatures/',
'.',
)
):
pass
else:
ret.append(p)
if 0:
tgz, mupdf_location = get_mupdf_tgz()
if tgz:
ret.append((tgz, mupdf_tgz))
else:
log(f'Not including MuPDF .tgz in sdist.')
return ret
classifier = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Operating System :: MacOS',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux',
'Programming Language :: C',
'Programming Language :: C++',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: Implementation :: CPython',
'Topic :: Utilities',
'Topic :: Multimedia :: Graphics',
'Topic :: Software Development :: Libraries',
]
# We generate different wheels depending on PYMUPDF_SETUP_FLAVOUR.
#
version_p = '1.24.12'
version_b = '1.24.10'
if os.path.exists(f'{g_root}/{g_pymupdfb_sdist_marker}'):
# We are in a PyMuPDFb sdist. We specify a dummy package so that pip builds
# from sdists work - pip's build using PyMuPDF's sdist will already create
# the required binaries, but pip will still see `requires_dist` set to
# 'PyMuPDFb', so will also download and build PyMuPDFb's sdist.
#
log(f'Specifying dummy PyMuPDFb wheel.')
def get_requires_for_build_wheel(config_settings=None):
return list()
p = pipcl.Package(
'PyMuPDFb',
version_b,
summary = 'Dummy PyMuPDFb wheel',
description = '',
author = 'Artifex',
author_email = 'support@artifex.com',
license = 'GNU AFFERO GPL 3.0',
tag_python = 'py3',
)
else:
# A normal PyMuPDF package.
with open( f'{g_root}/README.md', encoding='utf-8') as f:
readme_p = f.read()
with open( f'{g_root}/READMEb.md', encoding='utf-8') as f:
readme_b = f.read()
with open( f'{g_root}/READMEd.md', encoding='utf-8') as f:
readme_d = f.read()
tag_python = None
requires_dist = None,
entry_points = None
if 'p' in PYMUPDF_SETUP_FLAVOUR:
version = version_p
name = 'PyMuPDF'
readme = readme_p
summary = 'A high performance Python library for data extraction, analysis, conversion & manipulation of PDF (and other) documents.'
if 'b' not in PYMUPDF_SETUP_FLAVOUR:
requires_dist = f'PyMuPDFb =={version_b}'
# Create a `pymupdf` command.
entry_points = textwrap.dedent('''
[console_scripts]
pymupdf = pymupdf.__main__:main
''')
elif 'b' in PYMUPDF_SETUP_FLAVOUR:
version = version_b
name = 'PyMuPDFb'
readme = readme_b
summary = 'MuPDF shared libraries for PyMuPDF.'
tag_python = 'py3'
elif 'd' in PYMUPDF_SETUP_FLAVOUR:
version = version_b
name = 'PyMuPDFd'
readme = readme_d
summary = 'MuPDF build-time files for PyMuPDF.'
tag_python = 'py3'
else:
assert 0, f'Unrecognised {PYMUPDF_SETUP_FLAVOUR=}.'
p = pipcl.Package(
name,
version,
summary = summary,
description = readme,
description_content_type = 'text/markdown',
classifier = classifier,
author = 'Artifex',
author_email = 'support@artifex.com',
requires_dist = requires_dist,
requires_python = '>=3.9',
license = 'GNU AFFERO GPL 3.0',
project_url = [
('Documentation, https://pymupdf.readthedocs.io/'),
('Source, https://github.com/pymupdf/pymupdf'),
('Tracker, https://github.com/pymupdf/PyMuPDF/issues'),
('Changelog, https://pymupdf.readthedocs.io/en/latest/changes.html'),
],
entry_points = entry_points,
fn_build=build,
fn_sdist=sdist,
tag_python=tag_python,
py_limited_api=g_py_limited_api,
# 30MB: 9 ZIP_DEFLATED
# 28MB: 9 ZIP_BZIP2
# 23MB: 9 ZIP_LZMA
#wheel_compression = zipfile.ZIP_DEFLATED if (darwin or pyodide) else zipfile.ZIP_LZMA,
wheel_compresslevel = 9,
)
def get_requires_for_build_wheel(config_settings=None):
'''
Adds to pyproject.toml:[build-system]:requires, allowing programmatic
control over what packages we require.
'''
def platform_release_tuple():
r = platform.release()
r = r.split('.')
r = tuple(int(i) for i in r)
log(f'platform_release_tuple() returning {r=}.')
return r
ret = list()
libclang = os.environ.get('PYMUPDF_SETUP_LIBCLANG')
if libclang:
print(f'Overriding to use {libclang=}.')
ret.append(libclang)
elif openbsd:
print(f'OpenBSD: libclang not available via pip; assuming `pkg_add py3-llvm`.')
elif darwin and platform.machine() == 'arm64':
print(f'MacOS/arm64: forcing use of libclang 16.0.6 because 18.1.1 known to fail with `clang.cindex.TranslationUnitLoadError: Error parsing translation unit.`')
ret.append('libclang==16.0.6')
elif darwin and platform_release_tuple() < (18,):
# There are still of problems when building on old macos.
ret.append('libclang==14.0.6')
else:
ret.append('libclang')
if msys2:
print(f'msys2: pip install of swig does not build; assuming `pacman -S swig`.')
elif openbsd:
print(f'OpenBSD: pip install of swig does not build; assuming `pkg_add swig`.')
else:
ret.append( 'swig')
return ret
if PYMUPDF_SETUP_URL_WHEEL:
def build_wheel(
wheel_directory,
config_settings=None,
metadata_directory=None,
p=p,
):
'''
Instead of building wheel, we look for and copy a wheel from location
specified by PYMUPDF_SETUP_URL_WHEEL.
'''
log(f'{PYMUPDF_SETUP_URL_WHEEL=}')
log(f'{p.wheel_name()=}')
url = PYMUPDF_SETUP_URL_WHEEL
if url.startswith(('http://', 'https://')):
leaf = p.wheel_name()
out_path = f'{wheel_directory}{leaf}'
out_path_temp = out_path + '-'
if url.endswith('/'):
url += leaf
log(f'Downloading from {url=} to {out_path_temp=}.')
urllib.request.urlretrieve(url, out_path_temp)
elif url.startswith(f'file://'):
in_path = url[len('file://'):]
log(f'{in_path=}')
if in_path.endswith('/'):
# Look for matching wheel within this directory.
wheels = glob.glob(f'{in_path}*.whl')
log(f'{len(wheels)=}')
for in_path in wheels:
log(f'{in_path=}')
leaf = os.path.basename(in_path)
if p.wheel_name_match(leaf):
log(f'Match: {in_path=}')
break
else:
message = f'Cannot find matching for {p.wheel_name()=} in ({len(wheels)=}):\n'
wheels_text = ''
for wheel in wheels:
wheels_text += f' {wheel}\n'
assert 0, f'Cannot find matching for {p.wheel_name()=} in:\n{wheels_text}'
else:
leaf = os.path.basename(in_path)
out_path = os.path.join(wheel_directory, leaf)
out_path_temp = out_path + '-'
log(f'Copying from {in_path=} to {out_path_temp=}.')
shutil.copy2(in_path, out_path_temp)
else:
assert 0, f'Unrecognised prefix in {PYMUPDF_SETUP_URL_WHEEL=}.'
log(f'Renaming from:\n {out_path_temp}\nto:\n {out_path}.')
os.rename(out_path_temp, out_path)
return os.path.basename(out_path)
else:
build_wheel = p.build_wheel
build_sdist = p.build_sdist
if __name__ == '__main__':
p.handle_argv(sys.argv)
| 48,119 | Python | .py | 1,146 | 32.453752 | 172 | 0.591096 | pymupdf/PyMuPDF | 5,009 | 480 | 32 | AGPL-3.0 | 9/5/2024, 5:12:54 PM (Europe/Amsterdam) |
21,294 | pipcl.py | pymupdf_PyMuPDF/pipcl.py | '''
Python packaging operations, including PEP-517 support, for use by a `setup.py`
script.
The intention is to take care of as many packaging details as possible so that
setup.py contains only project-specific information, while also giving as much
flexibility as possible.
For example we provide a function `build_extension()` that can be used to build
a SWIG extension, but we also give access to the located compiler/linker so
that a `setup.py` script can take over the details itself.
Run doctests with: `python -m doctest pipcl.py`
'''
import base64
import glob
import hashlib
import inspect
import io
import os
import platform
import re
import shutil
import site
import subprocess
import sys
import sysconfig
import tarfile
import textwrap
import time
import zipfile
import wdev
class Package:
'''
Our constructor takes a definition of a Python package similar to that
passed to `distutils.core.setup()` or `setuptools.setup()` (name, version,
summary etc) plus callbacks for building, getting a list of sdist
filenames, and cleaning.
We provide methods that can be used to implement a Python package's
`setup.py` supporting PEP-517.
We also support basic command line handling for use
with a legacy (pre-PEP-517) pip, as implemented
by legacy distutils/setuptools and described in:
https://pip.pypa.io/en/stable/reference/build-system/setup-py/
Here is a `doctest` example of using pipcl to create a SWIG extension
module. Requires `swig`.
Create an empty test directory:
>>> import os
>>> import shutil
>>> shutil.rmtree('pipcl_test', ignore_errors=1)
>>> os.mkdir('pipcl_test')
Create a `setup.py` which uses `pipcl` to define an extension module.
>>> import textwrap
>>> with open('pipcl_test/setup.py', 'w') as f:
... _ = f.write(textwrap.dedent("""
... import sys
... import pipcl
...
... def build():
... so_leaf = pipcl.build_extension(
... name = 'foo',
... path_i = 'foo.i',
... outdir = 'build',
... )
... return [
... ('build/foo.py', 'foo/__init__.py'),
... ('cli.py', 'foo/__main__.py'),
... (f'build/{so_leaf}', f'foo/'),
... ('README', '$dist-info/'),
... (b'Hello world', 'foo/hw.txt'),
... ]
...
... def sdist():
... return [
... 'foo.i',
... 'bar.i',
... 'setup.py',
... 'pipcl.py',
... 'wdev.py',
... 'README',
... (b'Hello word2', 'hw2.txt'),
... ]
...
... p = pipcl.Package(
... name = 'foo',
... version = '1.2.3',
... fn_build = build,
... fn_sdist = sdist,
... entry_points = (
... { 'console_scripts': [
... 'foo_cli = foo.__main__:main',
... ],
... }),
... )
...
... build_wheel = p.build_wheel
... build_sdist = p.build_sdist
...
... # Handle old-style setup.py command-line usage:
... if __name__ == '__main__':
... p.handle_argv(sys.argv)
... """))
Create the files required by the above `setup.py` - the SWIG `.i` input
file, the README file, and copies of `pipcl.py` and `wdev.py`.
>>> with open('pipcl_test/foo.i', 'w') as f:
... _ = f.write(textwrap.dedent("""
... %include bar.i
... %{
... #include <stdio.h>
... #include <string.h>
... int bar(const char* text)
... {
... printf("bar(): text: %s\\\\n", text);
... int len = (int) strlen(text);
... printf("bar(): len=%i\\\\n", len);
... fflush(stdout);
... return len;
... }
... %}
... int bar(const char* text);
... """))
>>> with open('pipcl_test/bar.i', 'w') as f:
... _ = f.write( '\\n')
>>> with open('pipcl_test/README', 'w') as f:
... _ = f.write(textwrap.dedent("""
... This is Foo.
... """))
>>> with open('pipcl_test/cli.py', 'w') as f:
... _ = f.write(textwrap.dedent("""
... def main():
... print('pipcl_test:main().')
... if __name__ == '__main__':
... main()
... """))
>>> root = os.path.dirname(__file__)
>>> _ = shutil.copy2(f'{root}/pipcl.py', 'pipcl_test/pipcl.py')
>>> _ = shutil.copy2(f'{root}/wdev.py', 'pipcl_test/wdev.py')
Use `setup.py`'s command-line interface to build and install the extension
module into root `pipcl_test/install`.
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py --root install install',
... shell=1, check=1)
The actual install directory depends on `sysconfig.get_path('platlib')`:
>>> if windows():
... install_dir = 'pipcl_test/install'
... else:
... install_dir = f'pipcl_test/install/{sysconfig.get_path("platlib").lstrip(os.sep)}'
>>> assert os.path.isfile( f'{install_dir}/foo/__init__.py')
Create a test script which asserts that Python function call `foo.bar(s)`
returns the length of `s`, and run it with `PYTHONPATH` set to the install
directory:
>>> with open('pipcl_test/test.py', 'w') as f:
... _ = f.write(textwrap.dedent("""
... import sys
... import foo
... text = 'hello'
... print(f'test.py: calling foo.bar() with text={text!r}')
... sys.stdout.flush()
... l = foo.bar(text)
... print(f'test.py: foo.bar() returned: {l}')
... assert l == len(text)
... """))
>>> r = subprocess.run(
... f'{sys.executable} pipcl_test/test.py',
... shell=1, check=1, text=1,
... stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
... env=os.environ | dict(PYTHONPATH=install_dir),
... )
>>> print(r.stdout)
test.py: calling foo.bar() with text='hello'
bar(): text: hello
bar(): len=5
test.py: foo.bar() returned: 5
<BLANKLINE>
Check that building sdist and wheel succeeds. For now we don't attempt to
check that the sdist and wheel actually work.
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py sdist',
... shell=1, check=1)
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
... shell=1, check=1)
Check that rebuild does nothing.
>>> t0 = os.path.getmtime('pipcl_test/build/foo.py')
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
... shell=1, check=1)
>>> t = os.path.getmtime('pipcl_test/build/foo.py')
>>> assert t == t0
Check that touching bar.i forces rebuild.
>>> os.utime('pipcl_test/bar.i')
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
... shell=1, check=1)
>>> t = os.path.getmtime('pipcl_test/build/foo.py')
>>> assert t > t0
Check that touching foo.i.cpp does not run swig, but does recompile/link.
>>> t0 = time.time()
>>> os.utime('pipcl_test/build/foo.i.cpp')
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} setup.py bdist_wheel',
... shell=1, check=1)
>>> assert os.path.getmtime('pipcl_test/build/foo.py') <= t0
>>> so = glob.glob('pipcl_test/build/*.so')
>>> assert len(so) == 1
>>> so = so[0]
>>> assert os.path.getmtime(so) > t0
Check `entry_points` causes creation of command `foo_cli` when we install
from our wheel using pip. [As of 2024-02-24 using pipcl's CLI interface
directly with `setup.py install` does not support entry points.]
>>> print('Creating venv.', file=sys.stderr)
>>> _ = subprocess.run(
... f'cd pipcl_test && {sys.executable} -m venv pylocal',
... shell=1, check=1)
>>> print('Installing from wheel into venv using pip.', file=sys.stderr)
>>> _ = subprocess.run(
... f'. pipcl_test/pylocal/bin/activate && pip install pipcl_test/dist/*.whl',
... shell=1, check=1)
>>> print('Running foo_cli.', file=sys.stderr)
>>> _ = subprocess.run(
... f'. pipcl_test/pylocal/bin/activate && foo_cli',
... shell=1, check=1)
Wheels and sdists
Wheels:
We generate wheels according to:
https://packaging.python.org/specifications/binary-distribution-format/
* `{name}-{version}.dist-info/RECORD` uses sha256 hashes.
* We do not generate other `RECORD*` files such as
`RECORD.jws` or `RECORD.p7s`.
* `{name}-{version}.dist-info/WHEEL` has:
* `Wheel-Version: 1.0`
* `Root-Is-Purelib: false`
* No support for signed wheels.
Sdists:
We generate sdist's according to:
https://packaging.python.org/specifications/source-distribution-format/
'''
def __init__(self,
name,
version,
*,
platform = None,
supported_platform = None,
summary = None,
description = None,
description_content_type = None,
keywords = None,
home_page = None,
download_url = None,
author = None,
author_email = None,
maintainer = None,
maintainer_email = None,
license = None,
classifier = None,
requires_dist = None,
requires_python = None,
requires_external = None,
project_url = None,
provides_extra = None,
entry_points = None,
root = None,
fn_build = None,
fn_clean = None,
fn_sdist = None,
tag_python = None,
tag_abi = None,
tag_platform = None,
py_limited_api = None,
wheel_compression = zipfile.ZIP_DEFLATED,
wheel_compresslevel = None,
):
'''
The initial args before `root` define the package
metadata and closely follow the definitions in:
https://packaging.python.org/specifications/core-metadata/
Args:
name:
A string, the name of the Python package.
version:
A string, the version of the Python package. Also see PEP-440
`Version Identification and Dependency Specification`.
platform:
A string or list of strings.
supported_platform:
A string or list of strings.
summary:
A string, short description of the package.
description:
A string. If contains newlines, a detailed description of the
package. Otherwise the path of a file containing the detailed
description of the package.
description_content_type:
A string describing markup of `description` arg. For example
`text/markdown; variant=GFM`.
keywords:
A string containing comma-separated keywords.
home_page:
URL of home page.
download_url:
Where this version can be downloaded from.
author:
Author.
author_email:
Author email.
maintainer:
Maintainer.
maintainer_email:
Maintainer email.
license:
A string containing the license text. Written into metadata
file `COPYING`. Is also written into metadata itself if not
multi-line.
classifier:
A string or list of strings. Also see:
* https://pypi.org/pypi?%3Aaction=list_classifiers
* https://pypi.org/classifiers/
requires_dist:
A string or list of strings. Also see PEP-508.
requires_python:
A string or list of strings.
requires_external:
A string or list of strings.
project_url:
A string or list of strings, each of the form: `{name}, {url}`.
provides_extra:
A string or list of strings.
entry_points:
String or dict specifying *.dist-info/entry_points.txt, for
example:
```
[console_scripts]
foo_cli = foo.__main__:main
```
or:
{ 'console_scripts': [
'foo_cli = foo.__main__:main',
],
}
See: https://packaging.python.org/en/latest/specifications/entry-points/
root:
Root of package, defaults to current directory.
fn_build:
A function taking no args, or a single `config_settings` dict
arg (as described in PEP-517), that builds the package.
Should return a list of items; each item should be a tuple
`(from_, to_)`, or a single string `path` which is treated as
the tuple `(path, path)`.
`from_` can be a string or a `bytes`. If a string it should
be the path to a file; a relative path is treated as relative
to `root`. If a `bytes` it is the contents of the file to be
added.
`to_` identifies what the file should be called within a wheel
or when installing. If `to_` ends with `/`, the leaf of `from_`
is appended to it (and `from_` must not be a `bytes`).
Initial `$dist-info/` in `_to` is replaced by
`{name}-{version}.dist-info/`; this is useful for license files
etc.
Initial `$data/` in `_to` is replaced by
`{name}-{version}.data/`. We do not enforce particular
subdirectories, instead it is up to `fn_build()` to specify
specific subdirectories such as `purelib`, `headers`,
`scripts`, `data` etc.
If we are building a wheel (e.g. `python setup.py bdist_wheel`,
or PEP-517 pip calls `self.build_wheel()`), we add file `from_`
to the wheel archive with name `to_`.
If we are installing (e.g. `install` command in
the argv passed to `self.handle_argv()`), then
we copy `from_` to `{sitepackages}/{to_}`, where
`sitepackages` is the installation directory, the
default being `sysconfig.get_path('platlib')` e.g.
`myvenv/lib/python3.9/site-packages/`.
fn_clean:
A function taking a single arg `all_` that cleans generated
files. `all_` is true iff `--all` is in argv.
For safety and convenience, can also returns a list of
files/directory paths to be deleted. Relative paths are
interpreted as relative to `root`. All paths are asserted to be
within `root`.
fn_sdist:
A function taking no args, or a single `config_settings` dict
arg (as described in PEP517), that returns a list of items to
be copied into the sdist. The list should be in the same format
as returned by `fn_build`.
It can be convenient to use `pipcl.git_items()`.
The specification for sdists requires that the list contains
`pyproject.toml`; we enforce this with a diagnostic rather than
raising an exception, to allow legacy command-line usage.
tag_python:
First element of wheel tag defined in PEP-425. If None we use
`cp{version}`.
For example if code works with any Python version, one can use
'py3'.
tag_abi:
Second element of wheel tag defined in PEP-425. If None we use
`none`.
tag_platform:
Third element of wheel tag defined in PEP-425. Default
is `os.environ('AUDITWHEEL_PLAT')` if set, otherwise
derived from `sysconfig.get_platform()` (was
`setuptools.distutils.util.get_platform(), before that
`distutils.util.get_platform()` as specified in the PEP), e.g.
`openbsd_7_0_amd64`.
For pure python packages use: `tag_platform=any`
py_limited_api:
If true we build wheels that use the Python Limited API. We use
the version of `sys.executable` to define `Py_LIMITED_API` when
compiling extensions, and use ABI tag `abi3` in the wheel name
if argument `tag_abi` is None.
wheel_compression:
Used as `zipfile.ZipFile()`'s `compression` parameter when
creating wheels.
wheel_compresslevel:
Used as `zipfile.ZipFile()`'s `compresslevel` parameter when
creating wheels.
'''
assert name
assert version
def assert_str( v):
if v is not None:
assert isinstance( v, str), f'Not a string: {v!r}'
def assert_str_or_multi( v):
if v is not None:
assert isinstance( v, (str, tuple, list)), f'Not a string, tuple or list: {v!r}'
assert_str( name)
assert_str( version)
assert_str_or_multi( platform)
assert_str_or_multi( supported_platform)
assert_str( summary)
assert_str( description)
assert_str( description_content_type)
assert_str( keywords)
assert_str( home_page)
assert_str( download_url)
assert_str( author)
assert_str( author_email)
assert_str( maintainer)
assert_str( maintainer_email)
assert_str( license)
assert_str_or_multi( classifier)
assert_str_or_multi( requires_dist)
assert_str( requires_python)
assert_str_or_multi( requires_external)
assert_str_or_multi( project_url)
assert_str_or_multi( provides_extra)
# https://packaging.python.org/en/latest/specifications/core-metadata/.
assert re.match('([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$', name, re.IGNORECASE), \
f'Bad name: {name!r}'
_assert_version_pep_440(version)
# https://packaging.python.org/en/latest/specifications/binary-distribution-format/
if tag_python:
assert '-' not in tag_python
if tag_abi:
assert '-' not in tag_abi
if tag_platform:
assert '-' not in tag_platform
self.name = name
self.version = version
self.platform = platform
self.supported_platform = supported_platform
self.summary = summary
self.description = description
self.description_content_type = description_content_type
self.keywords = keywords
self.home_page = home_page
self.download_url = download_url
self.author = author
self.author_email = author_email
self.maintainer = maintainer
self.maintainer_email = maintainer_email
self.license = license
self.classifier = classifier
self.requires_dist = requires_dist
self.requires_python = requires_python
self.requires_external = requires_external
self.project_url = project_url
self.provides_extra = provides_extra
self.entry_points = entry_points
self.root = os.path.abspath(root if root else os.getcwd())
self.fn_build = fn_build
self.fn_clean = fn_clean
self.fn_sdist = fn_sdist
self.tag_python_ = tag_python
self.tag_abi_ = tag_abi
self.tag_platform_ = tag_platform
self.py_limited_api = py_limited_api
self.wheel_compression = wheel_compression
self.wheel_compresslevel = wheel_compresslevel
def build_wheel(self,
wheel_directory,
config_settings=None,
metadata_directory=None,
):
'''
A PEP-517 `build_wheel()` function.
Also called by `handle_argv()` to handle the `bdist_wheel` command.
Returns leafname of generated wheel within `wheel_directory`.
'''
log2(
f' wheel_directory={wheel_directory!r}'
f' config_settings={config_settings!r}'
f' metadata_directory={metadata_directory!r}'
)
wheel_name = self.wheel_name()
path = f'{wheel_directory}/{wheel_name}'
# Do a build and get list of files to copy into the wheel.
#
items = list()
if self.fn_build:
items = self._call_fn_build(config_settings)
log2(f'Creating wheel: {path}')
os.makedirs(wheel_directory, exist_ok=True)
record = _Record()
with zipfile.ZipFile(path, 'w', self.wheel_compression, self.wheel_compresslevel) as z:
def add(from_, to_):
if isinstance(from_, str):
z.write(from_, to_)
record.add_file(from_, to_)
elif isinstance(from_, bytes):
z.writestr(to_, from_)
record.add_content(from_, to_)
else:
assert 0
def add_str(content, to_):
add(content.encode('utf8'), to_)
dist_info_dir = self._dist_info_dir()
# Add the files returned by fn_build().
#
for item in items:
from_, (to_abs, to_rel) = self._fromto(item)
add(from_, to_rel)
# Add <name>-<version>.dist-info/WHEEL.
#
add_str(
f'Wheel-Version: 1.0\n'
f'Generator: pipcl\n'
f'Root-Is-Purelib: false\n'
f'Tag: {self.wheel_tag_string()}\n'
,
f'{dist_info_dir}/WHEEL',
)
# Add <name>-<version>.dist-info/METADATA.
#
add_str(self._metainfo(), f'{dist_info_dir}/METADATA')
# Add <name>-<version>.dist-info/COPYING.
if self.license:
add_str(self.license, f'{dist_info_dir}/COPYING')
# Add <name>-<version>.dist-info/entry_points.txt.
entry_points_text = self._entry_points_text()
if entry_points_text:
add_str(entry_points_text, f'{dist_info_dir}/entry_points.txt')
# Update <name>-<version>.dist-info/RECORD. This must be last.
#
z.writestr(f'{dist_info_dir}/RECORD', record.get(f'{dist_info_dir}/RECORD'))
st = os.stat(path)
log1( f'Have created wheel size={st.st_size}: {path}')
if g_verbose >= 2:
with zipfile.ZipFile(path, compression=self.wheel_compression) as z:
log2(f'Contents are:')
for zi in sorted(z.infolist(), key=lambda z: z.filename):
log2(f' {zi.file_size: 10d} {zi.filename}')
return os.path.basename(path)
def build_sdist(self,
sdist_directory,
formats,
config_settings=None,
):
'''
A PEP-517 `build_sdist()` function.
Also called by `handle_argv()` to handle the `sdist` command.
Returns leafname of generated archive within `sdist_directory`.
'''
log2(
f' sdist_directory={sdist_directory!r}'
f' formats={formats!r}'
f' config_settings={config_settings!r}'
)
if formats and formats != 'gztar':
raise Exception( f'Unsupported: formats={formats}')
items = list()
if self.fn_sdist:
if inspect.signature(self.fn_sdist).parameters:
items = self.fn_sdist(config_settings)
else:
items = self.fn_sdist()
prefix = f'{self.name}-{self.version}'
os.makedirs(sdist_directory, exist_ok=True)
tarpath = f'{sdist_directory}/{prefix}.tar.gz'
log2(f'Creating sdist: {tarpath}')
with tarfile.open(tarpath, 'w:gz') as tar:
names_in_tar = list()
def check_name(name):
if name in names_in_tar:
raise Exception(f'Name specified twice: {name}')
names_in_tar.append(name)
def add(from_, name):
check_name(name)
if isinstance(from_, str):
log2( f'Adding file: {os.path.relpath(from_)} => {name}')
tar.add( from_, f'{prefix}/{name}', recursive=False)
elif isinstance(from_, bytes):
log2( f'Adding: {name}')
ti = tarfile.TarInfo(f'{prefix}/{name}')
ti.size = len(from_)
ti.mtime = time.time()
tar.addfile(ti, io.BytesIO(from_))
else:
assert 0
def add_string(text, name):
textb = text.encode('utf8')
return add(textb, name)
found_pyproject_toml = False
for item in items:
from_, (to_abs, to_rel) = self._fromto(item)
if isinstance(from_, bytes):
add(from_, to_rel)
else:
if from_.startswith(f'{os.path.abspath(sdist_directory)}/'):
# Source files should not be inside <sdist_directory>.
assert 0, f'Path is inside sdist_directory={sdist_directory}: {from_!r}'
assert os.path.exists(from_), f'Path does not exist: {from_!r}'
assert os.path.isfile(from_), f'Path is not a file: {from_!r}'
if to_rel == 'pyproject.toml':
found_pyproject_toml = True
add(from_, to_rel)
if not found_pyproject_toml:
log0(f'Warning: no pyproject.toml specified.')
# Always add a PKG-INFO file.
add_string(self._metainfo(), 'PKG-INFO')
if self.license:
if 'COPYING' in names_in_tar:
log2(f'Not writing .license because file already in sdist: COPYING')
else:
add_string(self.license, 'COPYING')
log1( f'Have created sdist: {tarpath}')
return os.path.basename(tarpath)
def wheel_tag_string(self):
'''
Returns <tag_python>-<tag_abi>-<tag_platform>.
'''
return f'{self.tag_python()}-{self.tag_abi()}-{self.tag_platform()}'
def tag_python(self):
'''
Get two-digit python version, e.g. 'cp3.8' for python-3.8.6.
'''
if self.tag_python_:
return self.tag_python_
else:
return 'cp' + ''.join(platform.python_version().split('.')[:2])
def tag_abi(self):
'''
ABI tag.
'''
if self.tag_abi_:
return self.tag_abi_
elif self.py_limited_api:
return 'abi3'
else:
return 'none'
def tag_platform(self):
'''
Find platform tag used in wheel filename.
'''
ret = self.tag_platform_
log0(f'From self.tag_platform_: {ret=}.')
if not ret:
# Prefer this to PEP-425. Appears to be undocumented,
# but set in manylinux docker images and appears
# to be used by cibuildwheel and auditwheel, e.g.
# https://github.com/rapidsai/shared-action-workflows/issues/80
ret = os.environ.get( 'AUDITWHEEL_PLAT')
log0(f'From AUDITWHEEL_PLAT: {ret=}.')
if not ret:
# Notes:
#
# PEP-425. On Linux gives `linux_x86_64` which is rejected by
# pypi.org.
#
# On local MacOS/arm64 mac-mini have seen sysconfig.get_platform()
# unhelpfully return `macosx-10.9-universal2` if `python3` is the
# system Python /usr/bin/python3; this happens if we source `.
# /etc/profile`.
#
ret = sysconfig.get_platform()
ret = ret.replace('-', '_').replace('.', '_').lower()
log0(f'From sysconfig.get_platform(): {ret=}.')
# We need to patch things on MacOS.
#
# E.g. `foo-1.2.3-cp311-none-macosx_13_x86_64.whl`
# causes `pip` to fail with: `not a supported wheel on this
# platform`. We seem to need to add `_0` to the OS version.
#
m = re.match( '^(macosx_[0-9]+)(_[^0-9].+)$', ret)
if m:
ret2 = f'{m.group(1)}_0{m.group(2)}'
log0(f'After macos patch, changing from {ret!r} to {ret2!r}.')
ret = ret2
log0( f'tag_platform(): returning {ret=}.')
return ret
def wheel_name(self):
return f'{self.name}-{self.version}-{self.tag_python()}-{self.tag_abi()}-{self.tag_platform()}.whl'
def wheel_name_match(self, wheel):
'''
Returns true if `wheel` matches our wheel. We basically require the
name to be the same, except that we accept platform tags that contain
extra items (see pep-0600/), for example we return true with:
self: foo-cp38-none-manylinux2014_x86_64.whl
wheel: foo-cp38-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
'''
log2(f'{wheel=}')
assert wheel.endswith('.whl')
wheel2 = wheel[:-len('.whl')]
name, version, tag_python, tag_abi, tag_platform = wheel2.split('-')
py_limited_api_compatible = False
if self.py_limited_api and tag_abi == 'abi3':
# Allow lower tag_python number.
m = re.match('cp([0-9]+)', tag_python)
tag_python_int = int(m.group(1))
m = re.match('cp([0-9]+)', self.tag_python())
tag_python_int_self = int(m.group(1))
if tag_python_int <= tag_python_int_self:
# This wheel uses Python stable ABI same or older than ours, so
# we can use it.
log2(f'py_limited_api; {tag_python=} compatible with {self.tag_python()=}.')
py_limited_api_compatible = True
log2(f'{self.name == name=}')
log2(f'{self.version == version=}')
log2(f'{self.tag_python() == tag_python=} {self.tag_python()=} {tag_python=}')
log2(f'{py_limited_api_compatible=}')
log2(f'{self.tag_abi() == tag_abi=}')
log2(f'{self.tag_platform() in tag_platform.split(".")=}')
log2(f'{self.tag_platform()=}')
log2(f'{tag_platform.split(".")=}')
ret = (1
and self.name == name
and self.version == version
and (self.tag_python() == tag_python or py_limited_api_compatible)
and self.tag_abi() == tag_abi
and self.tag_platform() in tag_platform.split('.')
)
log2(f'Returning {ret=}.')
return ret
def _entry_points_text(self):
if self.entry_points:
if isinstance(self.entry_points, str):
return self.entry_points
ret = ''
for key, values in self.entry_points.items():
ret += f'[{key}]\n'
for value in values:
ret += f'{value}\n'
return ret
def _call_fn_build( self, config_settings=None):
assert self.fn_build
log2(f'calling self.fn_build={self.fn_build}')
if inspect.signature(self.fn_build).parameters:
ret = self.fn_build(config_settings)
else:
ret = self.fn_build()
assert isinstance( ret, (list, tuple)), \
f'Expected list/tuple from {self.fn_build} but got: {ret!r}'
return ret
def _argv_clean(self, all_):
'''
Called by `handle_argv()`.
'''
if not self.fn_clean:
return
paths = self.fn_clean(all_)
if paths:
if isinstance(paths, str):
paths = paths,
for path in paths:
if not os.path.isabs(path):
path = ps.path.join(self.root, path)
path = os.path.abspath(path)
assert path.startswith(self.root+os.sep), \
f'path={path!r} does not start with root={self.root+os.sep!r}'
log2(f'Removing: {path}')
shutil.rmtree(path, ignore_errors=True)
def install(self, record_path=None, root=None):
'''
Called by `handle_argv()` to handle `install` command..
'''
log2( f'{record_path=} {root=}')
# Do a build and get list of files to install.
#
items = list()
if self.fn_build:
items = self._call_fn_build( dict())
root2 = install_dir(root)
log2( f'{root2=}')
log1( f'Installing into: {root2!r}')
dist_info_dir = self._dist_info_dir()
if not record_path:
record_path = f'{root2}/{dist_info_dir}/RECORD'
record = _Record()
def add_file(from_, to_abs, to_rel):
os.makedirs( os.path.dirname( to_abs), exist_ok=True)
if isinstance(from_, bytes):
log2(f'Copying content into {to_abs}.')
with open(to_abs, 'wb') as f:
f.write(from_)
record.add_content(from_, to_rel)
else:
log0(f'{from_=}')
log2(f'Copying from {os.path.relpath(from_, self.root)} to {to_abs}')
shutil.copy2( from_, to_abs)
record.add_file(from_, to_rel)
def add_str(content, to_abs, to_rel):
log2( f'Writing to: {to_abs}')
os.makedirs( os.path.dirname( to_abs), exist_ok=True)
with open( to_abs, 'w') as f:
f.write( content)
record.add_content(content, to_rel)
for item in items:
from_, (to_abs, to_rel) = self._fromto(item)
log0(f'{from_=} {to_abs=} {to_rel=}')
to_abs2 = f'{root2}/{to_rel}'
add_file( from_, to_abs2, to_rel)
add_str( self._metainfo(), f'{root2}/{dist_info_dir}/METADATA', f'{dist_info_dir}/METADATA')
if self.license:
add_str( self.license, f'{root2}/{dist_info_dir}/COPYING', f'{dist_info_dir}/COPYING')
entry_points_text = self._entry_points_text()
if entry_points_text:
add_str(
entry_points_text,
f'{root2}/{dist_info_dir}/entry_points.txt',
f'{dist_info_dir}/entry_points.txt',
)
log2( f'Writing to: {record_path}')
with open(record_path, 'w') as f:
f.write(record.get())
log2(f'Finished.')
def _argv_dist_info(self, root):
'''
Called by `handle_argv()`. There doesn't seem to be any documentation
for `setup.py dist_info`, but it appears to be like `egg_info` except
it writes to a slightly different directory.
'''
if root is None:
root = f'{self.name}-{self.version}.dist-info'
self._write_info(f'{root}/METADATA')
if self.license:
with open( f'{root}/COPYING', 'w') as f:
f.write( self.license)
def _argv_egg_info(self, egg_base):
'''
Called by `handle_argv()`.
'''
if egg_base is None:
egg_base = '.'
self._write_info(f'{egg_base}/.egg-info')
def _write_info(self, dirpath=None):
'''
Writes egg/dist info to files in directory `dirpath` or `self.root` if
`None`.
'''
if dirpath is None:
dirpath = self.root
log2(f'Creating files in directory {dirpath}')
os.makedirs(dirpath, exist_ok=True)
with open(os.path.join(dirpath, 'PKG-INFO'), 'w') as f:
f.write(self._metainfo())
# These don't seem to be required?
#
#with open(os.path.join(dirpath, 'SOURCES.txt', 'w') as f:
# pass
#with open(os.path.join(dirpath, 'dependency_links.txt', 'w') as f:
# pass
#with open(os.path.join(dirpath, 'top_level.txt', 'w') as f:
# f.write(f'{self.name}\n')
#with open(os.path.join(dirpath, 'METADATA', 'w') as f:
# f.write(self._metainfo())
def handle_argv(self, argv):
'''
Attempt to handles old-style (pre PEP-517) command line passed by
old releases of pip to a `setup.py` script, and manual running of
`setup.py`.
This is partial support at best.
'''
global g_verbose
#log2(f'argv: {argv}')
class ArgsRaise:
pass
class Args:
'''
Iterates over argv items.
'''
def __init__( self, argv):
self.items = iter( argv)
def next( self, eof=ArgsRaise):
'''
Returns next arg. If no more args, we return <eof> or raise an
exception if <eof> is ArgsRaise.
'''
try:
return next( self.items)
except StopIteration:
if eof is ArgsRaise:
raise Exception('Not enough args')
return eof
command = None
opt_all = None
opt_dist_dir = 'dist'
opt_egg_base = None
opt_formats = None
opt_install_headers = None
opt_record = None
opt_root = None
args = Args(argv[1:])
while 1:
arg = args.next(None)
if arg is None:
break
elif arg in ('-h', '--help', '--help-commands'):
log0(textwrap.dedent('''
Usage:
[<options>...] <command> [<options>...]
Commands:
bdist_wheel
Creates a wheel called
<dist-dir>/<name>-<version>-<details>.whl, where
<dist-dir> is "dist" or as specified by --dist-dir,
and <details> encodes ABI and platform etc.
clean
Cleans build files.
dist_info
Creates files in <name>-<version>.dist-info/ or
directory specified by --egg-base.
egg_info
Creates files in .egg-info/ or directory
directory specified by --egg-base.
install
Builds and installs. Writes installation
information to <record> if --record was
specified.
sdist
Make a source distribution:
<dist-dir>/<name>-<version>.tar.gz
Options:
--all
Used by "clean".
--compile
Ignored.
--dist-dir | -d <dist-dir>
Default is "dist".
--egg-base <egg-base>
Used by "egg_info".
--formats <formats>
Used by "sdist".
--install-headers <directory>
Ignored.
--python-tag <python-tag>
Ignored.
--record <record>
Used by "install".
--root <path>
Used by "install".
--single-version-externally-managed
Ignored.
--verbose -v
Extra diagnostics.
Other:
windows-vs [-y <year>] [-v <version>] [-g <grade] [--verbose]
Windows only; looks for matching Visual Studio.
windows-python [-v <version>] [--verbose]
Windows only; looks for matching Python.
'''))
return
elif arg in ('bdist_wheel', 'clean', 'dist_info', 'egg_info', 'install', 'sdist'):
assert command is None, 'Two commands specified: {command} and {arg}.'
command = arg
elif arg == '--all': opt_all = True
elif arg == '--compile': pass
elif arg == '--dist-dir' or arg == '-d': opt_dist_dir = args.next()
elif arg == '--egg-base': opt_egg_base = args.next()
elif arg == '--formats': opt_formats = args.next()
elif arg == '--install-headers': opt_install_headers = args.next()
elif arg == '--python-tag': pass
elif arg == '--record': opt_record = args.next()
elif arg == '--root': opt_root = args.next()
elif arg == '--single-version-externally-managed': pass
elif arg == '--verbose' or arg == '-v': g_verbose += 1
elif arg == 'windows-vs':
command = arg
break
elif arg == 'windows-python':
command = arg
break
else:
raise Exception(f'Unrecognised arg: {arg}')
assert command, 'No command specified'
log1(f'Handling command={command}')
if 0: pass
elif command == 'bdist_wheel': self.build_wheel(opt_dist_dir)
elif command == 'clean': self._argv_clean(opt_all)
elif command == 'dist_info': self._argv_dist_info(opt_egg_base)
elif command == 'egg_info': self._argv_egg_info(opt_egg_base)
elif command == 'install': self.install(opt_record, opt_root)
elif command == 'sdist': self.build_sdist(opt_dist_dir, opt_formats)
elif command == 'windows-python':
version = None
while 1:
arg = args.next(None)
if arg is None:
break
elif arg == '-v':
version = args.next()
elif arg == '--verbose':
g_verbose += 1
else:
assert 0, f'Unrecognised {arg=}'
python = wdev.WindowsPython(version=version)
print(f'Python is:\n{python.description_ml(" ")}')
elif command == 'windows-vs':
grade = None
version = None
year = None
while 1:
arg = args.next(None)
if arg is None:
break
elif arg == '-g':
grade = args.next()
elif arg == '-v':
version = args.next()
elif arg == '-y':
year = args.next()
elif arg == '--verbose':
g_verbose += 1
else:
assert 0, f'Unrecognised {arg=}'
vs = wdev.WindowsVS(year=year, grade=grade, version=version)
print(f'Visual Studio is:\n{vs.description_ml(" ")}')
else:
assert 0, f'Unrecognised command: {command}'
log2(f'Finished handling command: {command}')
def __str__(self):
return ('{'
f'name={self.name!r}'
f' version={self.version!r}'
f' platform={self.platform!r}'
f' supported_platform={self.supported_platform!r}'
f' summary={self.summary!r}'
f' description={self.description!r}'
f' description_content_type={self.description_content_type!r}'
f' keywords={self.keywords!r}'
f' home_page={self.home_page!r}'
f' download_url={self.download_url!r}'
f' author={self.author!r}'
f' author_email={self.author_email!r}'
f' maintainer={self.maintainer!r}'
f' maintainer_email={self.maintainer_email!r}'
f' license={self.license!r}'
f' classifier={self.classifier!r}'
f' requires_dist={self.requires_dist!r}'
f' requires_python={self.requires_python!r}'
f' requires_external={self.requires_external!r}'
f' project_url={self.project_url!r}'
f' provides_extra={self.provides_extra!r}'
f' root={self.root!r}'
f' fn_build={self.fn_build!r}'
f' fn_sdist={self.fn_sdist!r}'
f' fn_clean={self.fn_clean!r}'
f' tag_python={self.tag_python_!r}'
f' tag_abi={self.tag_abi_!r}'
f' tag_platform={self.tag_platform_!r}'
'}'
)
def _dist_info_dir( self):
return f'{self.name}-{self.version}.dist-info'
def _metainfo(self):
'''
Returns text for `.egg-info/PKG-INFO` file, or `PKG-INFO` in an sdist
`.tar.gz` file, or `...dist-info/METADATA` in a wheel.
'''
# 2021-04-30: Have been unable to get multiline content working on
# test.pypi.org so we currently put the description as the body after
# all the other headers.
#
ret = ['']
def add(key, value):
if value is None:
return
if isinstance( value, (tuple, list)):
for v in value:
add( key, v)
return
if key == 'License' and '\n' in value:
# This is ok because we write `self.license` into
# *.dist-info/COPYING.
#
log1( f'Omitting license because contains newline(s).')
return
assert '\n' not in value, f'key={key} value contains newline: {value!r}'
if key == 'Project-URL':
assert value.count(',') == 1, f'For {key=}, should have one comma in {value!r}.'
ret[0] += f'{key}: {value}\n'
#add('Description', self.description)
add('Metadata-Version', '2.1')
# These names are from:
# https://packaging.python.org/specifications/core-metadata/
#
for name in (
'Name',
'Version',
'Platform',
'Supported-Platform',
'Summary',
'Description-Content-Type',
'Keywords',
'Home-page',
'Download-URL',
'Author',
'Author-email',
'Maintainer',
'Maintainer-email',
'License',
'Classifier',
'Requires-Dist',
'Requires-Python',
'Requires-External',
'Project-URL',
'Provides-Extra',
):
identifier = name.lower().replace( '-', '_')
add( name, getattr( self, identifier))
ret = ret[0]
# Append description as the body
if self.description:
if '\n' in self.description:
description_text = self.description.strip()
else:
with open(self.description) as f:
description_text = f.read()
ret += '\n' # Empty line separates headers from body.
ret += description_text
ret += '\n'
return ret
def _path_relative_to_root(self, path, assert_within_root=True):
'''
Returns `(path_abs, path_rel)`, where `path_abs` is absolute path and
`path_rel` is relative to `self.root`.
Interprets `path` as relative to `self.root` if not absolute.
We use `os.path.realpath()` to resolve any links.
if `assert_within_root` is true, assert-fails if `path` is not within
`self.root`.
'''
if os.path.isabs(path):
p = path
else:
p = os.path.join(self.root, path)
p = os.path.realpath(os.path.abspath(p))
if assert_within_root:
assert p.startswith(self.root+os.sep) or p == self.root, \
f'Path not within root={self.root+os.sep!r}: {path=} {p=}'
p_rel = os.path.relpath(p, self.root)
return p, p_rel
def _fromto(self, p):
'''
Returns `(from_, (to_abs, to_rel))`.
If `p` is a string we convert to `(p, p)`. Otherwise we assert that
`p` is a tuple `(from_, to_)` where `from_` is str/bytes and `to_` is
str. If `from_` is a bytes it is contents of file to add, otherwise the
path of an existing file; non-absolute paths are assumed to be relative
to `self.root`. If `to_` is empty or ends with `/`, we append the leaf
of `from_` (which must be a str).
If `to_` starts with `$dist-info/`, we replace this with
`self._dist_info_dir()`.
If `to_` starts with `$data/`, we replace this with
`{self.name}-{self.version}.data/`.
We assert that `to_abs` is `within self.root`.
`to_rel` is derived from the `to_abs` and is relative to self.root`.
'''
ret = None
if isinstance(p, str):
p = p, p
assert isinstance(p, tuple) and len(p) == 2
from_, to_ = p
assert isinstance(from_, (str, bytes))
assert isinstance(to_, str)
if to_.endswith('/') or to_=='':
to_ += os.path.basename(from_)
prefix = '$dist-info/'
if to_.startswith( prefix):
to_ = f'{self._dist_info_dir()}/{to_[ len(prefix):]}'
prefix = '$data/'
if to_.startswith( prefix):
to_ = f'{self.name}-{self.version}.data/{to_[ len(prefix):]}'
if isinstance(from_, str):
from_, _ = self._path_relative_to_root( from_, assert_within_root=False)
to_ = self._path_relative_to_root(to_)
assert isinstance(from_, (str, bytes))
log2(f'returning {from_=} {to_=}')
return from_, to_
def build_extension(
name,
path_i,
outdir,
builddir=None,
includes=None,
defines=None,
libpaths=None,
libs=None,
optimise=True,
debug=False,
compiler_extra='',
linker_extra='',
swig='swig',
cpp=True,
prerequisites_swig=None,
prerequisites_compile=None,
prerequisites_link=None,
infer_swig_includes=True,
py_limited_api=False,
):
'''
Builds a Python extension module using SWIG. Works on Windows, Linux, MacOS
and OpenBSD.
On Unix, sets rpath when linking shared libraries.
Args:
name:
Name of generated extension module.
path_i:
Path of input SWIG `.i` file. Internally we use swig to generate a
corresponding `.c` or `.cpp` file.
outdir:
Output directory for generated files:
* `{outdir}/{name}.py`
* `{outdir}/_{name}.so` # Unix
* `{outdir}/_{name}.*.pyd` # Windows
We return the leafname of the `.so` or `.pyd` file.
builddir:
Where to put intermediate files, for example the .cpp file
generated by swig and `.d` dependency files. Default is `outdir`.
includes:
A string, or a sequence of extra include directories to be prefixed
with `-I`.
defines:
A string, or a sequence of extra preprocessor defines to be
prefixed with `-D`.
libpaths
A string, or a sequence of library paths to be prefixed with
`/LIBPATH:` on Windows or `-L` on Unix.
libs
A string, or a sequence of library names. Each item is prefixed
with `-l` on non-Windows.
optimise:
Whether to use compiler optimisations.
debug:
Whether to build with debug symbols.
compiler_extra:
Extra compiler flags. Can be None.
linker_extra:
Extra linker flags. Can be None.
swig:
Base swig command.
cpp:
If true we tell SWIG to generate C++ code instead of C.
prerequisites_swig:
prerequisites_compile:
prerequisites_link:
[These are mainly for use on Windows. On other systems we
automatically generate dynamic dependencies using swig/compile/link
commands' `-MD` and `-MF` args.]
Sequences of extra input files/directories that should force
running of swig, compile or link commands if they are newer than
any existing generated SWIG `.i` file, compiled object file or
shared library file.
If present, the first occurrence of `True` or `False` forces re-run
or no re-run. Any occurrence of None is ignored. If an item is a
directory path we look for newest file within the directory tree.
If not a sequence, we convert into a single-item list.
prerequisites_swig
We use swig's -MD and -MF args to generate dynamic dependencies
automatically, so this is not usually required.
prerequisites_compile
prerequisites_link
On non-Windows we use cc's -MF and -MF args to generate dynamic
dependencies so this is not usually required.
infer_swig_includes:
If true, we extract `-I<path>` and `-I <path>` args from
`compile_extra` (also `/I` on windows) and use them with swig so
that it can see the same header files as C/C++. This is useful
when using enviromment variables such as `CC` and `CXX` to set
`compile_extra.
py_limited_api:
If true we build for current Python's limited API / stable ABI.
Returns the leafname of the generated library file within `outdir`, e.g.
`_{name}.so` on Unix or `_{name}.cp311-win_amd64.pyd` on Windows.
'''
if compiler_extra is None:
compiler_extra = ''
if linker_extra is None:
linker_extra = ''
if builddir is None:
builddir = outdir
includes_text = _flags( includes, '-I')
defines_text = _flags( defines, '-D')
libpaths_text = _flags( libpaths, '/LIBPATH:', '"') if windows() else _flags( libpaths, '-L')
libs_text = _flags( libs, '' if windows() else '-l')
path_cpp = f'{builddir}/{os.path.basename(path_i)}'
path_cpp += '.cpp' if cpp else '.c'
os.makedirs( outdir, exist_ok=True)
# Run SWIG.
if infer_swig_includes:
# Extract include flags from `compiler_extra`.
swig_includes_extra = ''
compiler_extra_items = compiler_extra.split()
i = 0
while i < len(compiler_extra_items):
item = compiler_extra_items[i]
# Swig doesn't seem to like a space after `I`.
if item == '-I' or (windows() and item == '/I'):
swig_includes_extra += f' -I{compiler_extra_items[i+1]}'
i += 1
elif item.startswith('-I') or (windows() and item.startswith('/I')):
swig_includes_extra += f' -I{compiler_extra_items[i][2:]}'
i += 1
swig_includes_extra = swig_includes_extra.strip()
deps_path = f'{path_cpp}.d'
prerequisites_swig2 = _get_prerequisites( deps_path)
run_if(
f'''
{swig}
-Wall
{"-c++" if cpp else ""}
-python
-module {name}
-outdir {outdir}
-o {path_cpp}
-MD -MF {deps_path}
{includes_text}
{swig_includes_extra}
{path_i}
'''
,
path_cpp,
path_i,
prerequisites_swig,
prerequisites_swig2,
)
so_suffix = _so_suffix(use_so_versioning = not py_limited_api)
path_so_leaf = f'_{name}{so_suffix}'
path_so = f'{outdir}/{path_so_leaf}'
py_limited_api2 = current_py_limited_api() if py_limited_api else None
if windows():
path_obj = f'{path_so}.obj'
permissive = '/permissive-'
EHsc = '/EHsc'
T = '/Tp' if cpp else '/Tc'
optimise2 = '/DNDEBUG /O2' if optimise else '/D_DEBUG'
debug2 = ''
if debug:
debug2 = '/Zi' # Generate .pdb.
# debug2 = '/Z7' # Embed debug info in .obj files.
py_limited_api3 = f'/DPy_LIMITED_API={py_limited_api2}' if py_limited_api2 else ''
# As of 2023-08-23, it looks like VS tools create slightly
# .dll's each time, even with identical inputs.
#
# Some info about this is at:
# https://nikhilism.com/post/2020/windows-deterministic-builds/.
# E.g. an undocumented linker flag `/Brepro`.
#
command, pythonflags = base_compiler(cpp=cpp)
command = f'''
{command}
# General:
/c # Compiles without linking.
{EHsc} # Enable "Standard C++ exception handling".
#/MD # Creates a multithreaded DLL using MSVCRT.lib.
{'/MDd' if debug else '/MD'}
# Input/output files:
{T}{path_cpp} # /Tp specifies C++ source file.
/Fo{path_obj} # Output file. codespell:ignore
# Include paths:
{includes_text}
{pythonflags.includes} # Include path for Python headers.
# Code generation:
{optimise2}
{debug2}
{permissive} # Set standard-conformance mode.
# Diagnostics:
#/FC # Display full path of source code files passed to cl.exe in diagnostic text.
/W3 # Sets which warning level to output. /W3 is IDE default.
/diagnostics:caret # Controls the format of diagnostic messages.
/nologo #
{defines_text}
{compiler_extra}
{py_limited_api3}
'''
run_if( command, path_obj, path_cpp, prerequisites_compile)
command, pythonflags = base_linker(cpp=cpp)
debug2 = '/DEBUG' if debug else ''
base, _ = os.path.splitext(path_so_leaf)
command = f'''
{command}
/DLL # Builds a DLL.
/EXPORT:PyInit__{name} # Exports a function.
/IMPLIB:{base}.lib # Overrides the default import library name.
{libpaths_text}
{pythonflags.ldflags}
/OUT:{path_so} # Specifies the output file name.
{debug2}
/nologo
{libs_text}
{path_obj}
{linker_extra}
'''
run_if( command, path_so, path_obj, prerequisites_link)
else:
# Not Windows.
#
command, pythonflags = base_compiler(cpp=cpp)
# setuptools on Linux seems to use slightly different compile flags:
#
# -fwrapv -O3 -Wall -O2 -g0 -DPY_CALL_TRAMPOLINE
#
general_flags = ''
if debug:
general_flags += ' -g'
if optimise:
general_flags += ' -O2 -DNDEBUG'
py_limited_api3 = f'-DPy_LIMITED_API={py_limited_api2}' if py_limited_api2 else ''
if darwin():
# MacOS's linker does not like `-z origin`.
rpath_flag = "-Wl,-rpath,@loader_path/"
# Avoid `Undefined symbols for ... "_PyArg_UnpackTuple" ...'.
general_flags += ' -undefined dynamic_lookup'
elif pyodide():
# Setting `-Wl,-rpath,'$ORIGIN',-z,origin` gives:
# emcc: warning: ignoring unsupported linker flag: `-rpath` [-Wlinkflags]
# wasm-ld: error: unknown -z value: origin
#
log0(f'pyodide: PEP-3149 suffix untested, so omitting. {_so_suffix()=}.')
path_so_leaf = f'_{name}.so'
path_so = f'{outdir}/{path_so_leaf}'
rpath_flag = ''
else:
rpath_flag = "-Wl,-rpath,'$ORIGIN',-z,origin"
path_so = f'{outdir}/{path_so_leaf}'
# Fun fact - on Linux, if the -L and -l options are before '{path_cpp}'
# they seem to be ignored...
#
prerequisites = list()
if pyodide():
# Looks like pyodide's `cc` can't compile and link in one invocation.
prerequisites_compile_path = f'{path_cpp}.o.d'
prerequisites += _get_prerequisites( prerequisites_compile_path)
command = f'''
{command}
-fPIC
{general_flags.strip()}
{pythonflags.includes}
{includes_text}
{defines_text}
-MD -MF {prerequisites_compile_path}
-c {path_cpp}
-o {path_cpp}.o
{compiler_extra}
{py_limited_api3}
'''
prerequisites_link_path = f'{path_cpp}.o.d'
prerequisites += _get_prerequisites( prerequisites_link_path)
ld, _ = base_linker(cpp=cpp)
command += f'''
&& {ld}
{path_cpp}.o
-o {path_so}
-MD -MF {prerequisites_link_path}
{rpath_flag}
{libpaths_text}
{libs_text}
{linker_extra}
{pythonflags.ldflags}
'''
else:
# We use compiler to compile and link in one command.
prerequisites_path = f'{path_so}.d'
prerequisites = _get_prerequisites(prerequisites_path)
command = f'''
{command}
-fPIC
-shared
{general_flags.strip()}
{pythonflags.includes}
{includes_text}
{defines_text}
{path_cpp}
-MD -MF {prerequisites_path}
-o {path_so}
{compiler_extra}
{libpaths_text}
{linker_extra}
{pythonflags.ldflags}
{libs_text}
{rpath_flag}
{py_limited_api3}
'''
command_was_run = run_if(
command,
path_so,
path_cpp,
prerequisites_compile,
prerequisites_link,
prerequisites,
)
if command_was_run and darwin():
# We need to patch up references to shared libraries in `libs`.
sublibraries = list()
for lib in () if libs is None else libs:
for libpath in libpaths:
found = list()
for suffix in '.so', '.dylib':
path = f'{libpath}/lib{os.path.basename(lib)}{suffix}'
if os.path.exists( path):
found.append( path)
if found:
assert len(found) == 1, f'More than one file matches lib={lib!r}: {found}'
sublibraries.append( found[0])
break
else:
log2(f'Warning: can not find path of lib={lib!r} in libpaths={libpaths}')
macos_patch( path_so, *sublibraries)
#run(f'ls -l {path_so}', check=0)
#run(f'file {path_so}', check=0)
return path_so_leaf
# Functions that might be useful.
#
def base_compiler(vs=None, pythonflags=None, cpp=False, use_env=True):
'''
Returns basic compiler command and PythonFlags.
Args:
vs:
Windows only. A `wdev.WindowsVS` instance or None to use default
`wdev.WindowsVS` instance.
pythonflags:
A `pipcl.PythonFlags` instance or None to use default
`pipcl.PythonFlags` instance.
cpp:
If true we return C++ compiler command instead of C. On Windows
this has no effect - we always return `cl.exe`.
use_env:
If true we return '$CC' or '$CXX' if the corresponding
environmental variable is set (without evaluating with `getenv()`
or `os.environ`).
Returns `(cc, pythonflags)`:
cc:
C or C++ command. On Windows this is of the form
`{vs.vcvars}&&{vs.cl}`; otherwise it is typically `cc` or `c++`.
pythonflags:
The `pythonflags` arg or a new `pipcl.PythonFlags` instance.
'''
if not pythonflags:
pythonflags = PythonFlags()
cc = None
if use_env:
if cpp:
if os.environ.get( 'CXX'):
cc = '$CXX'
else:
if os.environ.get( 'CC'):
cc = '$CC'
if cc:
pass
elif windows():
if not vs:
vs = wdev.WindowsVS()
cc = f'"{vs.vcvars}"&&"{vs.cl}"'
elif wasm():
cc = 'em++' if cpp else 'emcc'
else:
cc = 'c++' if cpp else 'cc'
cc = macos_add_cross_flags( cc)
return cc, pythonflags
def base_linker(vs=None, pythonflags=None, cpp=False, use_env=True):
'''
Returns basic linker command.
Args:
vs:
Windows only. A `wdev.WindowsVS` instance or None to use default
`wdev.WindowsVS` instance.
pythonflags:
A `pipcl.PythonFlags` instance or None to use default
`pipcl.PythonFlags` instance.
cpp:
If true we return C++ linker command instead of C. On Windows this
has no effect - we always return `link.exe`.
use_env:
If true we use `os.environ['LD']` if set.
Returns `(linker, pythonflags)`:
linker:
Linker command. On Windows this is of the form
`{vs.vcvars}&&{vs.link}`; otherwise it is typically `cc` or `c++`.
pythonflags:
The `pythonflags` arg or a new `pipcl.PythonFlags` instance.
'''
if not pythonflags:
pythonflags = PythonFlags()
linker = None
if use_env:
if os.environ.get( 'LD'):
linker = '$LD'
if linker:
pass
elif windows():
if not vs:
vs = wdev.WindowsVS()
linker = f'"{vs.vcvars}"&&"{vs.link}"'
elif wasm():
linker = 'em++' if cpp else 'emcc'
else:
linker = 'c++' if cpp else 'cc'
linker = macos_add_cross_flags( linker)
return linker, pythonflags
def git_items( directory, submodules=False):
'''
Returns list of paths for all files known to git within a `directory`.
Args:
directory:
Must be somewhere within a git checkout.
submodules:
If true we also include git submodules.
Returns:
A list of paths for all files known to git within `directory`. Each
path is relative to `directory`. `directory` must be somewhere within a
git checkout.
We run a `git ls-files` command internally.
This function can be useful for the `fn_sdist()` callback.
'''
command = 'cd ' + directory + ' && git ls-files'
if submodules:
command += ' --recurse-submodules'
log1(f'Running {command=}')
text = subprocess.check_output( command, shell=True)
ret = []
for path in text.decode('utf8').strip().split( '\n'):
path2 = os.path.join(directory, path)
# Sometimes git ls-files seems to list empty/non-existent directories
# within submodules.
#
if not os.path.exists(path2):
log2(f'Ignoring git ls-files item that does not exist: {path2}')
elif os.path.isdir(path2):
log2(f'Ignoring git ls-files item that is actually a directory: {path2}')
else:
ret.append(path)
return ret
def run( command, capture=False, check=1, verbose=1, env_extra=None, caller=1):
'''
Runs a command using `subprocess.run()`.
Args:
command:
A string, the command to run.
Multiple lines in `command` are treated as a single command.
* If a line starts with `#` it is discarded.
* If a line contains ` #`, the trailing text is discarded.
When running the command on Windows, newlines are replaced by
spaces; otherwise each line is terminated by a backslash character.
capture:
If true, we include the command's output in our return value.
check:
If true we raise an exception on error; otherwise we include the
command's returncode in our return value.
verbose:
If true we show the command.
env_extra:
None or dict to add to environ.
Returns:
check capture Return
--------------------------
false false returncode
false true (returncode, output)
true false None or raise exception
true true output or raise exception
'''
env = None
if env_extra:
env = os.environ.copy()
env.update(env_extra)
lines = _command_lines( command)
nl = '\n'
if verbose:
log1( f'Running: {nl.join(lines)}', caller=caller+1)
sep = ' ' if windows() else ' \\\n'
command2 = sep.join( lines)
cp = subprocess.run(
command2,
shell=True,
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.STDOUT if capture else None,
check=check,
encoding='utf8',
env=env,
)
if check:
return cp.stdout if capture else None
else:
return (cp.returncode, cp.stdout) if capture else cp.returncode
def darwin():
return sys.platform.startswith( 'darwin')
def windows():
return platform.system() == 'Windows'
def wasm():
return os.environ.get( 'OS') in ('wasm', 'wasm-mt')
def pyodide():
return os.environ.get( 'PYODIDE') == '1'
def linux():
return platform.system() == 'Linux'
def openbsd():
return platform.system() == 'OpenBSD'
class PythonFlags:
'''
Compile/link flags for the current python, for example the include path
needed to get `Python.h`.
The 'PIPCL_PYTHON_CONFIG' environment variable allows to override
the location of the python-config executable.
Members:
.includes:
String containing compiler flags for include paths.
.ldflags:
String containing linker flags for library paths.
'''
def __init__(self):
if windows():
wp = wdev.WindowsPython()
self.includes = f'/I"{wp.include}"'
self.ldflags = f'/LIBPATH:"{wp.libs}"'
elif pyodide():
_include_dir = os.environ[ 'PYO3_CROSS_INCLUDE_DIR']
_lib_dir = os.environ[ 'PYO3_CROSS_LIB_DIR']
self.includes = f'-I {_include_dir}'
self.ldflags = f'-L {_lib_dir}'
else:
python_config = os.environ.get("PIPCL_PYTHON_CONFIG")
if not python_config:
# We use python-config which appears to work better than pkg-config
# because it copes with multiple installed python's, e.g.
# manylinux_2014's /opt/python/cp*-cp*/bin/python*.
#
# But... on non-macos it seems that we should not attempt to specify
# libpython on the link command. The manylinux docker containers
# don't actually contain libpython.so, and it seems that this
# deliberate. And the link command runs ok.
#
python_exe = os.path.realpath( sys.executable)
if darwin():
# Basic install of dev tools with `xcode-select --install` doesn't
# seem to provide a `python3-config` or similar, but there is a
# `python-config.py` accessible via sysconfig.
#
# We try different possibilities and use the last one that
# works.
#
python_config = None
for pc in (
f'python3-config',
f'{sys.executable} {sysconfig.get_config_var("srcdir")}/python-config.py',
f'{python_exe}-config',
):
e = subprocess.run(
f'{pc} --includes',
shell=1,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=0,
).returncode
log2(f'{e=} from {pc!r}.')
if e == 0:
python_config = pc
assert python_config, f'Cannot find python-config'
else:
python_config = f'{python_exe}-config'
log2(f'Using {python_config=}.')
try:
self.includes = run( f'{python_config} --includes', capture=1, verbose=0).strip()
except Exception as e:
raise Exception('We require python development tools to be installed.') from e
self.ldflags = run( f'{python_config} --ldflags', capture=1, verbose=0).strip()
if linux():
# It seems that with python-3.10 on Linux, we can get an
# incorrect -lcrypt flag that on some systems (e.g. WSL)
# causes:
#
# ImportError: libcrypt.so.2: cannot open shared object file: No such file or directory
#
ldflags2 = self.ldflags.replace(' -lcrypt ', ' ')
if ldflags2 != self.ldflags:
log2(f'### Have removed `-lcrypt` from ldflags: {self.ldflags!r} -> {ldflags2!r}')
self.ldflags = ldflags2
log2(f'{self.includes=}')
log2(f'{self.ldflags=}')
def macos_add_cross_flags(command):
'''
If running on MacOS and environment variables ARCHFLAGS is set
(indicating we are cross-building, e.g. for arm64), returns
`command` with extra flags appended. Otherwise returns unchanged
`command`.
'''
if darwin():
archflags = os.environ.get( 'ARCHFLAGS')
if archflags:
command = f'{command} {archflags}'
log2(f'Appending ARCHFLAGS to command: {command}')
return command
return command
def macos_patch( library, *sublibraries):
'''
If running on MacOS, patches `library` so that all references to items in
`sublibraries` are changed to `@rpath/{leafname}`. Does nothing on other
platforms.
library:
Path of shared library.
sublibraries:
List of paths of shared libraries; these have typically been
specified with `-l` when `library` was created.
'''
log2( f'macos_patch(): library={library} sublibraries={sublibraries}')
if not darwin():
return
if not sublibraries:
return
subprocess.run( f'otool -L {library}', shell=1, check=1)
command = 'install_name_tool'
names = []
for sublibrary in sublibraries:
name = subprocess.run(
f'otool -D {sublibrary}',
shell=1,
check=1,
capture_output=1,
encoding='utf8',
).stdout.strip()
name = name.split('\n')
assert len(name) == 2 and name[0] == f'{sublibrary}:', f'{name=}'
name = name[1]
# strip trailing so_name.
leaf = os.path.basename(name)
m = re.match('^(.+[.]((so)|(dylib)))[0-9.]*$', leaf)
assert m
log2(f'Changing {leaf=} to {m.group(1)}')
leaf = m.group(1)
command += f' -change {name} @rpath/{leaf}'
command += f' {library}'
log2( f'Running: {command}')
subprocess.run( command, shell=1, check=1)
subprocess.run( f'otool -L {library}', shell=1, check=1)
# Internal helpers.
#
def _command_lines( command):
'''
Process multiline command by running through `textwrap.dedent()`, removes
comments (lines starting with `#` or ` #` until end of line), removes
entirely blank lines.
Returns list of lines.
'''
command = textwrap.dedent( command)
lines = []
for line in command.split( '\n'):
if line.startswith( '#'):
h = 0
else:
h = line.find( ' #')
if h >= 0:
line = line[:h]
if line.strip():
lines.append(line.rstrip())
return lines
def _cpu_name():
'''
Returns `x32` or `x64` depending on Python build.
'''
#log(f'sys.maxsize={hex(sys.maxsize)}')
return f'x{32 if sys.maxsize == 2**31 - 1 else 64}'
def run_if( command, out, *prerequisites):
'''
Runs a command only if the output file is not up to date.
Args:
command:
The command to run. We write this into a file <out>.cmd so that we
know to run a command if the command itself has changed.
out:
Path of the output file.
prerequisites:
List of prerequisite paths or true/false/None items. If an item
is None it is ignored, otherwise if an item is not a string we
immediately return it cast to a bool.
Returns:
True if we ran the command, otherwise None.
If the output file does not exist, the command is run:
>>> verbose(1)
1
>>> log_line_numbers(0)
>>> out = 'run_if_test_out'
>>> if os.path.exists( out):
... os.remove( out)
>>> if os.path.exists( f'{out}.cmd'):
... os.remove( f'{out}.cmd')
>>> run_if( f'touch {out}', out)
pipcl.py:run_if(): Running command because: File does not exist: 'run_if_test_out'
pipcl.py:run_if(): Running: touch run_if_test_out
True
If we repeat, the output file will be up to date so the command is not run:
>>> run_if( f'touch {out}', out)
pipcl.py:run_if(): Not running command because up to date: 'run_if_test_out'
If we change the command, the command is run:
>>> run_if( f'touch {out}', out)
pipcl.py:run_if(): Running command because: Command has changed
pipcl.py:run_if(): Running: touch run_if_test_out
True
If we add a prerequisite that is newer than the output, the command is run:
>>> time.sleep(1)
>>> prerequisite = 'run_if_test_prerequisite'
>>> run( f'touch {prerequisite}', caller=0)
pipcl.py:run(): Running: touch run_if_test_prerequisite
>>> run_if( f'touch {out}', out, prerequisite)
pipcl.py:run_if(): Running command because: Prerequisite is new: 'run_if_test_prerequisite'
pipcl.py:run_if(): Running: touch run_if_test_out
True
If we repeat, the output will be newer than the prerequisite, so the
command is not run:
>>> run_if( f'touch {out}', out, prerequisite)
pipcl.py:run_if(): Not running command because up to date: 'run_if_test_out'
'''
doit = False
cmd_path = f'{out}.cmd'
if not doit:
out_mtime = _fs_mtime( out)
if out_mtime == 0:
doit = f'File does not exist: {out!r}'
if not doit:
if os.path.isfile( cmd_path):
with open( cmd_path) as f:
cmd = f.read()
else:
cmd = None
if command != cmd:
if cmd is None:
doit = 'No previous command stored'
else:
doit = f'Command has changed'
if 0:
doit += f': {cmd!r} => {command!r}'
if not doit:
# See whether any prerequisites are newer than target.
def _make_prerequisites(p):
if isinstance( p, (list, tuple)):
return list(p)
else:
return [p]
prerequisites_all = list()
for p in prerequisites:
prerequisites_all += _make_prerequisites( p)
if 0:
log2( 'prerequisites_all:')
for i in prerequisites_all:
log2( f' {i!r}')
pre_mtime = 0
pre_path = None
for prerequisite in prerequisites_all:
if isinstance( prerequisite, str):
mtime = _fs_mtime_newest( prerequisite)
if mtime >= pre_mtime:
pre_mtime = mtime
pre_path = prerequisite
elif prerequisite is None:
pass
elif prerequisite:
doit = str(prerequisite)
break
if not doit:
if pre_mtime > out_mtime:
doit = f'Prerequisite is new: {pre_path!r}'
if doit:
# Remove `cmd_path` before we run the command, so any failure
# will force rerun next time.
#
try:
os.remove( cmd_path)
except Exception:
pass
log1( f'Running command because: {doit}')
run( command)
# Write the command we ran, into `cmd_path`.
with open( cmd_path, 'w') as f:
f.write( command)
return True
else:
log1( f'Not running command because up to date: {out!r}')
if 0:
log2( f'out_mtime={time.ctime(out_mtime)} pre_mtime={time.ctime(pre_mtime)}.'
f' pre_path={pre_path!r}: returning {ret!r}.'
)
def _get_prerequisites(path):
'''
Returns list of prerequisites from Makefile-style dependency file, e.g.
created by `cc -MD -MF <path>`.
'''
ret = list()
if os.path.isfile(path):
with open(path) as f:
for line in f:
for item in line.split():
if item.endswith( (':', '\\')):
continue
ret.append( item)
return ret
def _fs_mtime_newest( path):
'''
path:
If a file, returns mtime of the file. If a directory, returns mtime of
newest file anywhere within directory tree. Otherwise returns 0.
'''
ret = 0
if os.path.isdir( path):
for dirpath, dirnames, filenames in os.walk( path):
for filename in filenames:
path = os.path.join( dirpath, filename)
ret = max( ret, _fs_mtime( path))
else:
ret = _fs_mtime( path)
return ret
def _flags( items, prefix='', quote=''):
'''
Turns sequence into string, prefixing/quoting each item.
'''
if not items:
return ''
if isinstance( items, str):
items = items,
ret = ''
for item in items:
if ret:
ret += ' '
ret += f'{prefix}{quote}{item}{quote}'
return ret.strip()
def _fs_mtime( filename, default=0):
'''
Returns mtime of file, or `default` if error - e.g. doesn't exist.
'''
try:
return os.path.getmtime( filename)
except OSError:
return default
def _assert_version_pep_440(version):
assert re.match(
r'^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$',
version,
), \
f'Bad version: {version!r}.'
g_verbose = int(os.environ.get('PIPCL_VERBOSE', '1'))
def verbose(level=None):
'''
Sets verbose level if `level` is not None.
Returns verbose level.
'''
global g_verbose
if level is not None:
g_verbose = level
return g_verbose
g_log_line_numbers = True
def log_line_numbers(yes):
'''
Sets whether to include line numbers; helps with doctest.
'''
global g_log_line_numbers
g_log_line_numbers = bool(yes)
def log0(text='', caller=1):
_log(text, 0, caller+1)
def log1(text='', caller=1):
_log(text, 1, caller+1)
def log2(text='', caller=1):
_log(text, 2, caller+1)
def _log(text, level, caller):
'''
Logs lines with prefix.
'''
if level <= g_verbose:
fr = inspect.stack(context=0)[caller]
filename = relpath(fr.filename)
for line in text.split('\n'):
if g_log_line_numbers:
print(f'{filename}:{fr.lineno}:{fr.function}(): {line}', file=sys.stdout, flush=1)
else:
print(f'{filename}:{fr.function}(): {line}', file=sys.stdout, flush=1)
def relpath(path, start=None):
'''
A safe alternative to os.path.relpath(), avoiding an exception on Windows
if the drive needs to change - in this case we use os.path.abspath().
'''
if windows():
try:
return os.path.relpath(path, start)
except ValueError:
# os.path.relpath() fails if trying to change drives.
return os.path.abspath(path)
else:
return os.path.relpath(path, start)
def _so_suffix(use_so_versioning=True):
'''
Filename suffix for shared libraries is defined in pep-3149. The
pep claims to only address posix systems, but the recommended
sysconfig.get_config_var('EXT_SUFFIX') also seems to give the
right string on Windows.
If use_so_versioning is false, we return only the last component of
the suffix, which removes any version number, for example changing
`.cp312-win_amd64.pyd` to `.pyd`.
'''
# Example values:
# linux: .cpython-311-x86_64-linux-gnu.so
# macos: .cpython-311-darwin.so
# openbsd: .cpython-310.so
# windows .cp311-win_amd64.pyd
#
# Only Linux and Windows seem to identify the cpu. For example shared
# libraries in numpy-1.25.2-cp311-cp311-macosx_11_0_arm64.whl are called
# things like `numpy/core/_simd.cpython-311-darwin.so`.
#
ret = sysconfig.get_config_var('EXT_SUFFIX')
if not use_so_versioning:
# Use last component only.
ret = os.path.splitext(ret)[1]
return ret
def get_soname(path):
'''
If we are on Linux and `path` is softlink and points to a shared library
for which `objdump -p` contains 'SONAME', return the pointee. Otherwise
return `path`. Useful if Linux shared libraries have been created with
`-Wl,-soname,...`, where we need to embed the versioned library.
'''
if linux() and os.path.islink(path):
path2 = os.path.realpath(path)
if subprocess.run(f'objdump -p {path2}|grep SONAME', shell=1, check=0).returncode == 0:
return path2
elif openbsd():
# Return newest .so with version suffix.
sos = glob.glob(f'{path}.*')
log1(f'{sos=}')
sos2 = list()
for so in sos:
suffix = so[len(path):]
if not suffix or re.match('^[.][0-9.]*[0-9]$', suffix):
sos2.append(so)
sos2.sort(key=lambda p: os.path.getmtime(p))
log1(f'{sos2=}')
return sos2[-1]
return path
def current_py_limited_api():
'''
Returns value of PyLIMITED_API to build for current Python.
'''
a, b = map(int, platform.python_version().split('.')[:2])
return f'0x{a:02x}{b:02x}0000'
def install_dir(root=None):
'''
Returns install directory used by `install()`.
This will be `sysconfig.get_path('platlib')`, modified by `root` if not
None.
'''
# todo: for pure-python we should use sysconfig.get_path('purelib') ?
root2 = sysconfig.get_path('platlib')
if root:
if windows():
# If we are in a venv, `sysconfig.get_path('platlib')`
# can be absolute, e.g.
# `C:\\...\\venv-pypackage-3.11.1-64\\Lib\\site-packages`, so it's
# not clear how to append it to `root`. So we just use `root`.
return root
else:
# E.g. if `root` is `install' and `sysconfig.get_path('platlib')`
# is `/usr/local/lib/python3.9/site-packages`, we set `root2` to
# `install/usr/local/lib/python3.9/site-packages`.
#
return os.path.join( root, root2.lstrip( os.sep))
else:
return root2
class _Record:
'''
Internal - builds up text suitable for writing to a RECORD item, e.g.
within a wheel.
'''
def __init__(self):
self.text = ''
def add_content(self, content, to_, verbose=True):
if isinstance(content, str):
content = content.encode('utf8')
# Specification for the line we write is supposed to be in
# https://packaging.python.org/en/latest/specifications/binary-distribution-format
# but it's not very clear.
#
h = hashlib.sha256(content)
digest = h.digest()
digest = base64.urlsafe_b64encode(digest)
digest = digest.rstrip(b'=')
digest = digest.decode('utf8')
self.text += f'{to_},sha256={digest},{len(content)}\n'
if verbose:
log2(f'Adding {to_}')
def add_file(self, from_, to_):
log1(f'Adding file: {os.path.relpath(from_)} => {to_}')
with open(from_, 'rb') as f:
content = f.read()
self.add_content(content, to_, verbose=False)
def get(self, record_path=None):
'''
Returns contents of the RECORD file. If `record_path` is
specified we append a final line `<record_path>,,`; this can be
used to include the RECORD file itself in the contents, with
empty hash and size fields.
'''
ret = self.text
if record_path:
ret += f'{record_path},,\n'
return ret
| 93,511 | Python | .py | 2,212 | 30.250452 | 145 | 0.518816 | pymupdf/PyMuPDF | 5,009 | 480 | 32 | AGPL-3.0 | 9/5/2024, 5:12:54 PM (Europe/Amsterdam) |
21,295 | wdev.py | pymupdf_PyMuPDF/wdev.py | '''
Finds locations of Windows command-line development tools.
'''
import os
import platform
import glob
import re
import subprocess
import sys
import sysconfig
import textwrap
import pipcl
class WindowsVS:
r'''
Windows only. Finds locations of Visual Studio command-line tools. Assumes
VS2019-style paths.
Members and example values::
.year: 2019
.grade: Community
.version: 14.28.29910
.directory: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community
.vcvars: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat
.cl: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\bin\Hostx64\x64\cl.exe
.link: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\bin\Hostx64\x64\link.exe
.csc: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Roslyn\csc.exe
.msbuild: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\MSBuild.exe
.devenv: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.com
`.csc` is C# compiler; will be None if not found.
'''
def __init__( self, year=None, grade=None, version=None, cpu=None, verbose=False):
'''
Args:
year:
None or, for example, `2019`. If None we use environment
variable WDEV_VS_YEAR if set.
grade:
None or, for example, one of:
* `Community`
* `Professional`
* `Enterprise`
If None we use environment variable WDEV_VS_GRADE if set.
version:
None or, for example: `14.28.29910`. If None we use environment
variable WDEV_VS_VERSION if set.
cpu:
None or a `WindowsCpu` instance.
'''
def default(value, name):
if value is None:
name2 = f'WDEV_VS_{name.upper()}'
value = os.environ.get(name2)
if value is not None:
_log(f'Setting {name} from environment variable {name2}: {value!r}')
return value
try:
year = default(year, 'year')
grade = default(grade, 'grade')
version = default(version, 'version')
if not cpu:
cpu = WindowsCpu()
# Find `directory`.
#
pattern = f'C:\\Program Files*\\Microsoft Visual Studio\\{year if year else "2*"}\\{grade if grade else "*"}'
directories = glob.glob( pattern)
if verbose:
_log( f'Matches for: {pattern=}')
_log( f'{directories=}')
assert directories, f'No match found for: {pattern}'
directories.sort()
directory = directories[-1]
# Find `devenv`.
#
devenv = f'{directory}\\Common7\\IDE\\devenv.com'
assert os.path.isfile( devenv), f'Does not exist: {devenv}'
# Extract `year` and `grade` from `directory`.
#
# We use r'...' for regex strings because an extra level of escaping is
# required for backslashes.
#
regex = rf'^C:\\Program Files.*\\Microsoft Visual Studio\\([^\\]+)\\([^\\]+)'
m = re.match( regex, directory)
assert m, f'No match: {regex=} {directory=}'
year2 = m.group(1)
grade2 = m.group(2)
if year:
assert year2 == year
else:
year = year2
if grade:
assert grade2 == grade
else:
grade = grade2
# Find vcvars.bat.
#
vcvars = f'{directory}\\VC\\Auxiliary\\Build\\vcvars{cpu.bits}.bat'
assert os.path.isfile( vcvars), f'No match for: {vcvars}'
# Find cl.exe.
#
cl_pattern = f'{directory}\\VC\\Tools\\MSVC\\{version if version else "*"}\\bin\\Host{cpu.windows_name}\\{cpu.windows_name}\\cl.exe'
cl_s = glob.glob( cl_pattern)
assert cl_s, f'No match for: {cl_pattern}'
cl_s.sort()
cl = cl_s[ -1]
# Extract `version` from cl.exe's path.
#
m = re.search( rf'\\VC\\Tools\\MSVC\\([^\\]+)\\bin\\Host{cpu.windows_name}\\{cpu.windows_name}\\cl.exe$', cl)
assert m
version2 = m.group(1)
if version:
assert version2 == version
else:
version = version2
assert version
# Find link.exe.
#
link_pattern = f'{directory}\\VC\\Tools\\MSVC\\{version}\\bin\\Host{cpu.windows_name}\\{cpu.windows_name}\\link.exe'
link_s = glob.glob( link_pattern)
assert link_s, f'No match for: {link_pattern}'
link_s.sort()
link = link_s[ -1]
# Find csc.exe.
#
csc = None
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
if filename == 'csc.exe':
csc = os.path.join(dirpath, filename)
#_log(f'{csc=}')
#break
# Find MSBuild.exe.
#
msbuild = None
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
if filename == 'MSBuild.exe':
msbuild = os.path.join(dirpath, filename)
#_log(f'{csc=}')
#break
self.cl = cl
self.devenv = devenv
self.directory = directory
self.grade = grade
self.link = link
self.csc = csc
self.msbuild = msbuild
self.vcvars = vcvars
self.version = version
self.year = year
self.cpu = cpu
except Exception as e:
raise Exception( f'Unable to find Visual Studio') from e
def description_ml( self, indent=''):
'''
Return multiline description of `self`.
'''
ret = textwrap.dedent(f'''
year: {self.year}
grade: {self.grade}
version: {self.version}
directory: {self.directory}
vcvars: {self.vcvars}
cl: {self.cl}
link: {self.link}
csc: {self.csc}
msbuild: {self.msbuild}
devenv: {self.devenv}
cpu: {self.cpu}
''')
return textwrap.indent( ret, indent)
def __repr__( self):
return ' '.join( self._description())
class WindowsCpu:
'''
For Windows only. Paths and names that depend on cpu.
Members:
.bits
32 or 64.
.windows_subdir
Empty string or `x64/`.
.windows_name
`x86` or `x64`.
.windows_config
`x64` or `Win32`, e.g. for use in `/Build Release|x64`.
.windows_suffix
`64` or empty string.
'''
def __init__(self, name=None):
if not name:
name = _cpu_name()
self.name = name
if name == 'x32':
self.bits = 32
self.windows_subdir = ''
self.windows_name = 'x86'
self.windows_config = 'Win32'
self.windows_suffix = ''
elif name == 'x64':
self.bits = 64
self.windows_subdir = 'x64/'
self.windows_name = 'x64'
self.windows_config = 'x64'
self.windows_suffix = '64'
else:
assert 0, f'Unrecognised cpu name: {name}'
def __repr__(self):
return self.name
class WindowsPython:
'''
Windows only. Information about installed Python with specific word size
and version. Defaults to the currently-running Python.
Members:
.path:
Path of python binary.
.version:
`{major}.{minor}`, e.g. `3.9` or `3.11`. Same as `version` passed
to `__init__()` if not None, otherwise the inferred version.
.include:
Python include path.
.cpu:
A `WindowsCpu` instance, same as `cpu` passed to `__init__()` if
not None, otherwise the inferred cpu.
We parse the output from `py -0p` to find all available python
installations.
'''
def __init__( self, cpu=None, version=None, verbose=True):
'''
Args:
cpu:
A WindowsCpu instance. If None, we use whatever we are running
on.
version:
Two-digit Python version as a string such as `3.8`. If None we
use current Python's version.
verbose:
If true we show diagnostics.
'''
if cpu is None:
cpu = WindowsCpu(_cpu_name())
if version is None:
version = '.'.join(platform.python_version().split('.')[:2])
_log(f'Looking for Python {version=} {cpu.bits=}.')
if '.'.join(platform.python_version().split('.')[:2]) == version:
# Current python matches, so use it directly. This avoids problems
# on Github where experimental python-3.13 was not available via
# `py`, and is kept here in case a similar problems happens with
# future Python versions.
_log(f'{cpu=} {version=}: using {sys.executable=}.')
self.path = sys.executable
self.version = version
self.cpu = cpu
self.include = sysconfig.get_path('include')
else:
command = 'py -0p'
if verbose:
_log(f'{cpu=} {version=}: Running: {command}')
text = subprocess.check_output( command, shell=True, text=True)
for line in text.split('\n'):
#_log( f' {line}')
if m := re.match( '^ *-V:([0-9.]+)(-32)? ([*])? +(.+)$', line):
version2 = m.group(1)
bits = 32 if m.group(2) else 64
current = m.group(3)
path = m.group(4).strip()
elif m := re.match( '^ *-([0-9.]+)-((32)|(64)) +(.+)$', line):
version2 = m.group(1)
bits = int(m.group(2))
path = m.group(5).strip()
else:
if verbose:
_log( f'No match for {line=}')
continue
if verbose:
_log( f'{version2=} {bits=} {path=} from {line=}.')
if bits != cpu.bits or version2 != version:
continue
root = os.path.dirname(path)
if not os.path.exists(path):
# Sometimes it seems that the specified .../python.exe does not exist,
# and we have to change it to .../python<version>.exe.
#
assert path.endswith('.exe'), f'path={path!r}'
path2 = f'{path[:-4]}{version}.exe'
_log( f'Python {path!r} does not exist; changed to: {path2!r}')
assert os.path.exists( path2)
path = path2
self.path = path
self.version = version
self.cpu = cpu
command = f'{self.path} -c "import sysconfig; print(sysconfig.get_path(\'include\'))"'
_log(f'Finding Python include path by running {command=}.')
self.include = subprocess.check_output(command, shell=True, text=True).strip()
_log(f'Python include path is {self.include=}.')
#_log( f'pipcl.py:WindowsPython():\n{self.description_ml(" ")}')
break
else:
_log(f'Failed to find python matching cpu={cpu}.')
_log(f'Output from {command!r} was:\n{text}')
raise Exception( f'Failed to find python matching cpu={cpu} {version=}.')
# Oddly there doesn't seem to be a
# `sysconfig.get_path('libs')`, but it seems to be next
# to `includes`:
self.libs = os.path.abspath(f'{self.include}/../libs')
_log( f'WindowsPython:\n{self.description_ml(" ")}')
def description_ml(self, indent=''):
ret = textwrap.dedent(f'''
path: {self.path}
version: {self.version}
cpu: {self.cpu}
include: {self.include}
libs: {self.libs}
''')
return textwrap.indent( ret, indent)
def __repr__(self):
return f'path={self.path!r} version={self.version!r} cpu={self.cpu!r} include={self.include!r} libs={self.libs!r}'
# Internal helpers.
#
def _cpu_name():
'''
Returns `x32` or `x64` depending on Python build.
'''
#log(f'sys.maxsize={hex(sys.maxsize)}')
return f'x{32 if sys.maxsize == 2**31 - 1 else 64}'
def _log(text='', caller=1):
'''
Logs lines with prefix.
'''
pipcl.log1(text, caller+1)
| 13,541 | Python | .py | 327 | 28.82263 | 144 | 0.508922 | pymupdf/PyMuPDF | 5,009 | 480 | 32 | AGPL-3.0 | 9/5/2024, 5:12:54 PM (Europe/Amsterdam) |
21,296 | __main__.py | pymupdf_PyMuPDF/src/__main__.py | # -----------------------------------------------------------------------------
# Copyright 2020-2022, Harald Lieder, mailto:harald.lieder@outlook.com
# License: GNU AFFERO GPL 3.0, https://www.gnu.org/licenses/agpl-3.0.html
# Part of "PyMuPDF", Python bindings for "MuPDF" (http://mupdf.com), a
# lightweight PDF, XPS, and E-book viewer, renderer and toolkit which is
# maintained and developed by Artifex Software, Inc. https://artifex.com.
# -----------------------------------------------------------------------------
import argparse
import bisect
import os
import sys
import statistics
from typing import Dict, List, Set
from . import pymupdf
def mycenter(x):
return (" %s " % x).center(75, "-")
def recoverpix(doc, item):
"""Return image for a given XREF."""
x = item[0] # xref of PDF image
s = item[1] # xref of its /SMask
if s == 0: # no smask: use direct image output
return doc.extract_image(x)
def getimage(pix):
if pix.colorspace.n != 4:
return pix
tpix = pymupdf.Pixmap(pymupdf.csRGB, pix)
return tpix
# we need to reconstruct the alpha channel with the smask
pix1 = pymupdf.Pixmap(doc, x)
pix2 = pymupdf.Pixmap(doc, s) # create pixmap of the /SMask entry
"""Sanity check:
- both pixmaps must have the same rectangle
- both pixmaps must have alpha=0
- pix2 must consist of 1 byte per pixel
"""
if not (pix1.irect == pix2.irect and pix1.alpha == pix2.alpha == 0 and pix2.n == 1):
pymupdf.message("Warning: unsupported /SMask %i for %i:" % (s, x))
pymupdf.message(pix2)
pix2 = None
return getimage(pix1) # return the pixmap as is
pix = pymupdf.Pixmap(pix1) # copy of pix1, with an alpha channel added
pix.set_alpha(pix2.samples) # treat pix2.samples as the alpha values
pix1 = pix2 = None # free temp pixmaps
# we may need to adjust something for CMYK pixmaps here:
return getimage(pix)
def open_file(filename, password, show=False, pdf=True):
"""Open and authenticate a document."""
doc = pymupdf.open(filename)
if not doc.is_pdf and pdf is True:
sys.exit("this command supports PDF files only")
rc = -1
if not doc.needs_pass:
return doc
if password:
rc = doc.authenticate(password)
if not rc:
sys.exit("authentication unsuccessful")
if show is True:
pymupdf.message("authenticated as %s" % "owner" if rc > 2 else "user")
else:
sys.exit("'%s' requires a password" % doc.name)
return doc
def print_dict(item):
"""Print a Python dictionary."""
l = max([len(k) for k in item.keys()]) + 1
for k, v in item.items():
msg = "%s: %s" % (k.rjust(l), v)
pymupdf.message(msg)
def print_xref(doc, xref):
"""Print an object given by XREF number.
Simulate the PDF source in "pretty" format.
For a stream also print its size.
"""
pymupdf.message("%i 0 obj" % xref)
xref_str = doc.xref_object(xref)
pymupdf.message(xref_str)
if doc.xref_is_stream(xref):
temp = xref_str.split()
try:
idx = temp.index("/Length") + 1
size = temp[idx]
if size.endswith("0 R"):
size = "unknown"
except Exception:
size = "unknown"
pymupdf.message("stream\n...%s bytes" % size)
pymupdf.message("endstream")
pymupdf.message("endobj")
def get_list(rlist, limit, what="page"):
"""Transform a page / xref specification into a list of integers.
Args
----
rlist: (str) the specification
limit: maximum number, i.e. number of pages, number of objects
what: a string to be used in error messages
Returns
-------
A list of integers representing the specification.
"""
N = str(limit - 1)
rlist = rlist.replace("N", N).replace(" ", "")
rlist_arr = rlist.split(",")
out_list = []
for seq, item in enumerate(rlist_arr):
n = seq + 1
if item.isdecimal(): # a single integer
i = int(item)
if 1 <= i < limit:
out_list.append(int(item))
else:
sys.exit("bad %s specification at item %i" % (what, n))
continue
try: # this must be a range now, and all of the following must work:
i1, i2 = item.split("-") # will fail if not 2 items produced
i1 = int(i1) # will fail on non-integers
i2 = int(i2)
except Exception:
sys.exit("bad %s range specification at item %i" % (what, n))
if not (1 <= i1 < limit and 1 <= i2 < limit):
sys.exit("bad %s range specification at item %i" % (what, n))
if i1 == i2: # just in case: a range of equal numbers
out_list.append(i1)
continue
if i1 < i2: # first less than second
out_list += list(range(i1, i2 + 1))
else: # first larger than second
out_list += list(range(i1, i2 - 1, -1))
return out_list
def show(args):
doc = open_file(args.input, args.password, True)
size = os.path.getsize(args.input) / 1024
flag = "KB"
if size > 1000:
size /= 1024
flag = "MB"
size = round(size, 1)
meta = doc.metadata # pylint: disable=no-member
pymupdf.message(
"'%s', pages: %i, objects: %i, %g %s, %s, encryption: %s"
% (
args.input,
doc.page_count,
doc.xref_length() - 1,
size,
flag,
meta["format"],
meta["encryption"],
)
)
n = doc.is_form_pdf
if n > 0:
s = doc.get_sigflags()
pymupdf.message(
"document contains %i root form fields and is %ssigned"
% (n, "not " if s != 3 else "")
)
n = doc.embfile_count()
if n > 0:
pymupdf.message("document contains %i embedded files" % n)
pymupdf.message()
if args.catalog:
pymupdf.message(mycenter("PDF catalog"))
xref = doc.pdf_catalog()
print_xref(doc, xref)
pymupdf.message()
if args.metadata:
pymupdf.message(mycenter("PDF metadata"))
print_dict(doc.metadata) # pylint: disable=no-member
pymupdf.message()
if args.xrefs:
pymupdf.message(mycenter("object information"))
xrefl = get_list(args.xrefs, doc.xref_length(), what="xref")
for xref in xrefl:
print_xref(doc, xref)
pymupdf.message()
if args.pages:
pymupdf.message(mycenter("page information"))
pagel = get_list(args.pages, doc.page_count + 1)
for pno in pagel:
n = pno - 1
xref = doc.page_xref(n)
pymupdf.message("Page %i:" % pno)
print_xref(doc, xref)
pymupdf.message()
if args.trailer:
pymupdf.message(mycenter("PDF trailer"))
pymupdf.message(doc.pdf_trailer())
pymupdf.message()
doc.close()
def clean(args):
doc = open_file(args.input, args.password, pdf=True)
encryption = args.encryption
encrypt = ("keep", "none", "rc4-40", "rc4-128", "aes-128", "aes-256").index(
encryption
)
if not args.pages: # simple cleaning
doc.save(
args.output,
garbage=args.garbage,
deflate=args.compress,
pretty=args.pretty,
clean=args.sanitize,
ascii=args.ascii,
linear=args.linear,
encryption=encrypt,
owner_pw=args.owner,
user_pw=args.user,
permissions=args.permission,
)
return
# create sub document from page numbers
pages = get_list(args.pages, doc.page_count + 1)
outdoc = pymupdf.open()
for pno in pages:
n = pno - 1
outdoc.insert_pdf(doc, from_page=n, to_page=n)
outdoc.save(
args.output,
garbage=args.garbage,
deflate=args.compress,
pretty=args.pretty,
clean=args.sanitize,
ascii=args.ascii,
linear=args.linear,
encryption=encrypt,
owner_pw=args.owner,
user_pw=args.user,
permissions=args.permission,
)
doc.close()
outdoc.close()
return
def doc_join(args):
"""Join pages from several PDF documents."""
doc_list = args.input # a list of input PDFs
doc = pymupdf.open() # output PDF
for src_item in doc_list: # process one input PDF
src_list = src_item.split(",")
password = src_list[1] if len(src_list) > 1 else None
src = open_file(src_list[0], password, pdf=True)
pages = ",".join(src_list[2:]) # get 'pages' specifications
if pages: # if anything there, retrieve a list of desired pages
page_list = get_list(",".join(src_list[2:]), src.page_count + 1)
else: # take all pages
page_list = range(1, src.page_count + 1)
for i in page_list:
doc.insert_pdf(src, from_page=i - 1, to_page=i - 1) # copy each source page
src.close()
doc.save(args.output, garbage=4, deflate=True)
doc.close()
def embedded_copy(args):
"""Copy embedded files between PDFs."""
doc = open_file(args.input, args.password, pdf=True)
if not doc.can_save_incrementally() and (
not args.output or args.output == args.input
):
sys.exit("cannot save PDF incrementally")
src = open_file(args.source, args.pwdsource)
names = set(args.name) if args.name else set()
src_names = set(src.embfile_names())
if names:
if not names <= src_names:
sys.exit("not all names are contained in source")
else:
names = src_names
if not names:
sys.exit("nothing to copy")
intersect = names & set(doc.embfile_names()) # any equal name already in target?
if intersect:
sys.exit("following names already exist in receiving PDF: %s" % str(intersect))
for item in names:
info = src.embfile_info(item)
buff = src.embfile_get(item)
doc.embfile_add(
item,
buff,
filename=info["filename"],
ufilename=info["ufilename"],
desc=info["desc"],
)
pymupdf.message("copied entry '%s' from '%s'" % (item, src.name))
src.close()
if args.output and args.output != args.input:
doc.save(args.output, garbage=3)
else:
doc.saveIncr()
doc.close()
def embedded_del(args):
"""Delete an embedded file entry."""
doc = open_file(args.input, args.password, pdf=True)
if not doc.can_save_incrementally() and (
not args.output or args.output == args.input
):
sys.exit("cannot save PDF incrementally")
exception_types = (ValueError, pymupdf.mupdf.FzErrorBase)
if pymupdf.mupdf_version_tuple < (1, 24):
exception_types = ValueError
try:
doc.embfile_del(args.name)
except exception_types as e: # pylint: disable=catching-non-exception
sys.exit(f'no such embedded file {args.name!r}: {e}')
if not args.output or args.output == args.input:
doc.saveIncr()
else:
doc.save(args.output, garbage=1)
doc.close()
def embedded_get(args):
"""Retrieve contents of an embedded file."""
doc = open_file(args.input, args.password, pdf=True)
exception_types = (ValueError, pymupdf.mupdf.FzErrorBase)
if pymupdf.mupdf_version_tuple < (1, 24):
exception_types = ValueError
try:
stream = doc.embfile_get(args.name)
d = doc.embfile_info(args.name)
except exception_types as e: # pylint: disable=catching-non-exception
sys.exit(f'no such embedded file {args.name!r}: {e}')
filename = args.output if args.output else d["filename"]
with open(filename, "wb") as output:
output.write(stream)
pymupdf.message("saved entry '%s' as '%s'" % (args.name, filename))
doc.close()
def embedded_add(args):
"""Insert a new embedded file."""
doc = open_file(args.input, args.password, pdf=True)
if not doc.can_save_incrementally() and (
args.output is None or args.output == args.input
):
sys.exit("cannot save PDF incrementally")
try:
doc.embfile_del(args.name)
sys.exit("entry '%s' already exists" % args.name)
except Exception:
pass
if not os.path.exists(args.path) or not os.path.isfile(args.path):
sys.exit("no such file '%s'" % args.path)
with open(args.path, "rb") as f:
stream = f.read()
filename = args.path
ufilename = filename
if not args.desc:
desc = filename
else:
desc = args.desc
doc.embfile_add(
args.name, stream, filename=filename, ufilename=ufilename, desc=desc
)
if not args.output or args.output == args.input:
doc.saveIncr()
else:
doc.save(args.output, garbage=3)
doc.close()
def embedded_upd(args):
"""Update contents or metadata of an embedded file."""
doc = open_file(args.input, args.password, pdf=True)
if not doc.can_save_incrementally() and (
args.output is None or args.output == args.input
):
sys.exit("cannot save PDF incrementally")
try:
doc.embfile_info(args.name)
except Exception:
sys.exit("no such embedded file '%s'" % args.name)
if (
args.path is not None
and os.path.exists(args.path)
and os.path.isfile(args.path)
):
with open(args.path, "rb") as f:
stream = f.read()
else:
stream = None
if args.filename:
filename = args.filename
else:
filename = None
if args.ufilename:
ufilename = args.ufilename
elif args.filename:
ufilename = args.filename
else:
ufilename = None
if args.desc:
desc = args.desc
else:
desc = None
doc.embfile_upd(
args.name, stream, filename=filename, ufilename=ufilename, desc=desc
)
if args.output is None or args.output == args.input:
doc.saveIncr()
else:
doc.save(args.output, garbage=3)
doc.close()
def embedded_list(args):
"""List embedded files."""
doc = open_file(args.input, args.password, pdf=True)
names = doc.embfile_names()
if args.name is not None:
if args.name not in names:
sys.exit("no such embedded file '%s'" % args.name)
else:
pymupdf.message()
pymupdf.message(
"printing 1 of %i embedded file%s:"
% (len(names), "s" if len(names) > 1 else "")
)
pymupdf.message()
print_dict(doc.embfile_info(args.name))
pymupdf.message()
return
if not names:
pymupdf.message("'%s' contains no embedded files" % doc.name)
return
if len(names) > 1:
msg = "'%s' contains the following %i embedded files" % (doc.name, len(names))
else:
msg = "'%s' contains the following embedded file" % doc.name
pymupdf.message(msg)
pymupdf.message()
for name in names:
if not args.detail:
pymupdf.message(name)
continue
_ = doc.embfile_info(name)
print_dict(doc.embfile_info(name))
pymupdf.message()
doc.close()
def extract_objects(args):
"""Extract images and / or fonts from a PDF."""
if not args.fonts and not args.images:
sys.exit("neither fonts nor images requested")
doc = open_file(args.input, args.password, pdf=True)
if args.pages:
pages = get_list(args.pages, doc.page_count + 1)
else:
pages = range(1, doc.page_count + 1)
if not args.output:
out_dir = os.path.abspath(os.curdir)
else:
out_dir = args.output
if not (os.path.exists(out_dir) and os.path.isdir(out_dir)):
sys.exit("output directory %s does not exist" % out_dir)
font_xrefs = set() # already saved fonts
image_xrefs = set() # already saved images
for pno in pages:
if args.fonts:
itemlist = doc.get_page_fonts(pno - 1)
for item in itemlist:
xref = item[0]
if xref not in font_xrefs:
font_xrefs.add(xref)
fontname, ext, _, buffer = doc.extract_font(xref)
if ext == "n/a" or not buffer:
continue
outname = os.path.join(
out_dir, f"{fontname.replace(' ', '-')}-{xref}.{ext}"
)
with open(outname, "wb") as outfile:
outfile.write(buffer)
buffer = None
if args.images:
itemlist = doc.get_page_images(pno - 1)
for item in itemlist:
xref = item[0]
if xref not in image_xrefs:
image_xrefs.add(xref)
pix = recoverpix(doc, item)
if type(pix) is dict:
ext = pix["ext"]
imgdata = pix["image"]
outname = os.path.join(out_dir, "img-%i.%s" % (xref, ext))
with open(outname, "wb") as outfile:
outfile.write(imgdata)
else:
outname = os.path.join(out_dir, "img-%i.png" % xref)
pix2 = (
pix
if pix.colorspace.n < 4
else pymupdf.Pixmap(pymupdf.csRGB, pix)
)
pix2.save(outname)
if args.fonts:
pymupdf.message("saved %i fonts to '%s'" % (len(font_xrefs), out_dir))
if args.images:
pymupdf.message("saved %i images to '%s'" % (len(image_xrefs), out_dir))
doc.close()
def page_simple(page, textout, GRID, fontsize, noformfeed, skip_empty, flags):
eop = b"\n" if noformfeed else bytes([12])
text = page.get_text("text", flags=flags)
if not text:
if not skip_empty:
textout.write(eop) # write formfeed
return
textout.write(text.encode("utf8", errors="surrogatepass"))
textout.write(eop)
return
def page_blocksort(page, textout, GRID, fontsize, noformfeed, skip_empty, flags):
eop = b"\n" if noformfeed else bytes([12])
blocks = page.get_text("blocks", flags=flags)
if blocks == []:
if not skip_empty:
textout.write(eop) # write formfeed
return
blocks.sort(key=lambda b: (b[3], b[0]))
for b in blocks:
textout.write(b[4].encode("utf8", errors="surrogatepass"))
textout.write(eop)
return
def page_layout(page, textout, GRID, fontsize, noformfeed, skip_empty, flags):
eop = b"\n" if noformfeed else bytes([12])
# --------------------------------------------------------------------
def find_line_index(values: List[int], value: int) -> int:
"""Find the right row coordinate.
Args:
values: (list) y-coordinates of rows.
value: (int) lookup for this value (y-origin of char).
Returns:
y-ccordinate of appropriate line for value.
"""
i = bisect.bisect_right(values, value)
if i:
return values[i - 1]
raise RuntimeError("Line for %g not found in %s" % (value, values))
# --------------------------------------------------------------------
def curate_rows(rows: Set[int], GRID) -> List:
rows = list(rows)
rows.sort() # sort ascending
nrows = [rows[0]]
for h in rows[1:]:
if h >= nrows[-1] + GRID: # only keep significant differences
nrows.append(h)
return nrows # curated list of line bottom coordinates
def process_blocks(blocks: List[Dict], page: pymupdf.Page):
rows = set()
page_width = page.rect.width
page_height = page.rect.height
rowheight = page_height
left = page_width
right = 0
chars = []
for block in blocks:
for line in block["lines"]:
if line["dir"] != (1, 0): # ignore non-horizontal text
continue
x0, y0, x1, y1 = line["bbox"]
if y1 < 0 or y0 > page.rect.height: # ignore if outside CropBox
continue
# upd row height
height = y1 - y0
if rowheight > height:
rowheight = height
for span in line["spans"]:
if span["size"] <= fontsize:
continue
for c in span["chars"]:
x0, _, x1, _ = c["bbox"]
cwidth = x1 - x0
ox, oy = c["origin"]
oy = int(round(oy))
rows.add(oy)
ch = c["c"]
if left > ox and ch != " ":
left = ox # update left coordinate
if right < x1:
right = x1 # update right coordinate
# handle ligatures:
if cwidth == 0 and chars != []: # potential ligature
old_ch, old_ox, old_oy, old_cwidth = chars[-1]
if old_oy == oy: # ligature
if old_ch != chr(0xFB00): # previous "ff" char lig?
lig = joinligature(old_ch + ch) # no
# convert to one of the 3-char ligatures:
elif ch == "i":
lig = chr(0xFB03) # "ffi"
elif ch == "l":
lig = chr(0xFB04) # "ffl"
else: # something wrong, leave old char in place
lig = old_ch
chars[-1] = (lig, old_ox, old_oy, old_cwidth)
continue
chars.append((ch, ox, oy, cwidth)) # all chars on page
return chars, rows, left, right, rowheight
def joinligature(lig: str) -> str:
"""Return ligature character for a given pair / triple of characters.
Args:
lig: (str) 2/3 characters, e.g. "ff"
Returns:
Ligature, e.g. "ff" -> chr(0xFB00)
"""
if lig == "ff":
return chr(0xFB00)
elif lig == "fi":
return chr(0xFB01)
elif lig == "fl":
return chr(0xFB02)
elif lig == "ffi":
return chr(0xFB03)
elif lig == "ffl":
return chr(0xFB04)
elif lig == "ft":
return chr(0xFB05)
elif lig == "st":
return chr(0xFB06)
return lig
# --------------------------------------------------------------------
def make_textline(left, slot, minslot, lchars):
"""Produce the text of one output line.
Args:
left: (float) left most coordinate used on page
slot: (float) avg width of one character in any font in use.
minslot: (float) min width for the characters in this line.
chars: (list[tuple]) characters of this line.
Returns:
text: (str) text string for this line
"""
text = "" # we output this
old_char = ""
old_x1 = 0 # end coordinate of last char
old_ox = 0 # x-origin of last char
if minslot <= pymupdf.EPSILON:
raise RuntimeError("program error: minslot too small = %g" % minslot)
for c in lchars: # loop over characters
char, ox, _, cwidth = c
ox = ox - left # its (relative) start coordinate
x1 = ox + cwidth # ending coordinate
# eliminate overprint effect
if old_char == char and ox - old_ox <= cwidth * 0.2:
continue
# omit spaces overlapping previous char
if char == " " and (old_x1 - ox) / cwidth > 0.8:
continue
old_char = char
# close enough to previous?
if ox < old_x1 + minslot: # assume char adjacent to previous
text += char # append to output
old_x1 = x1 # new end coord
old_ox = ox # new origin.x
continue
# else next char starts after some gap:
# fill in right number of spaces, so char is positioned
# in the right slot of the line
if char == " ": # rest relevant for non-space only
continue
delta = int(ox / slot) - len(text)
if ox > old_x1 and delta > 1:
text += " " * delta
# now append char
text += char
old_x1 = x1 # new end coordinate
old_ox = ox # new origin
return text.rstrip()
# extract page text by single characters ("rawdict")
blocks = page.get_text("rawdict", flags=flags)["blocks"]
chars, rows, left, right, rowheight = process_blocks(blocks, page)
if chars == []:
if not skip_empty:
textout.write(eop) # write formfeed
return
# compute list of line coordinates - ignoring small (GRID) differences
rows = curate_rows(rows, GRID)
# sort all chars by x-coordinates, so every line will receive char info,
# sorted from left to right.
chars.sort(key=lambda c: c[1])
# populate the lines with their char info
lines = {} # key: y1-ccordinate, value: char list
for c in chars:
_, _, oy, _ = c
y = find_line_index(rows, oy) # y-coord of the right line
lchars = lines.get(y, []) # read line chars so far
lchars.append(c) # append this char
lines[y] = lchars # write back to line
# ensure line coordinates are ascending
keys = list(lines.keys())
keys.sort()
# -------------------------------------------------------------------------
# Compute "char resolution" for the page: the char width corresponding to
# 1 text char position on output - call it 'slot'.
# For each line, compute median of its char widths. The minimum across all
# lines is 'slot'.
# The minimum char width of each line is used to determine if spaces must
# be inserted in between two characters.
# -------------------------------------------------------------------------
slot = right - left
minslots = {}
for k in keys:
lchars = lines[k]
ccount = len(lchars)
if ccount < 2:
minslots[k] = 1
continue
widths = [c[3] for c in lchars]
widths.sort()
this_slot = statistics.median(widths) # take median value
if this_slot < slot:
slot = this_slot
minslots[k] = widths[0]
# compute line advance in text output
rowheight = rowheight * (rows[-1] - rows[0]) / (rowheight * len(rows)) * 1.2
rowpos = rows[0] # first line positioned here
textout.write(b"\n")
for k in keys: # walk through the lines
while rowpos < k: # honor distance between lines
textout.write(b"\n")
rowpos += rowheight
text = make_textline(left, slot, minslots[k], lines[k])
textout.write((text + "\n").encode("utf8", errors="surrogatepass"))
rowpos = k + rowheight
textout.write(eop) # write formfeed
def gettext(args):
doc = open_file(args.input, args.password, pdf=False)
pagel = get_list(args.pages, doc.page_count + 1)
output = args.output
if output is None:
filename, _ = os.path.splitext(doc.name)
output = filename + ".txt"
with open(output, "wb") as textout:
flags = pymupdf.TEXT_PRESERVE_LIGATURES | pymupdf.TEXT_PRESERVE_WHITESPACE
if args.convert_white:
flags ^= pymupdf.TEXT_PRESERVE_WHITESPACE
if args.noligatures:
flags ^= pymupdf.TEXT_PRESERVE_LIGATURES
if args.extra_spaces:
flags ^= pymupdf.TEXT_INHIBIT_SPACES
func = {
"simple": page_simple,
"blocks": page_blocksort,
"layout": page_layout,
}
for pno in pagel:
page = doc[pno - 1]
func[args.mode](
page,
textout,
args.grid,
args.fontsize,
args.noformfeed,
args.skip_empty,
flags=flags,
)
def _internal(args):
pymupdf.message('This is from PyMuPDF message().')
pymupdf.log('This is from PyMuPDF log().')
def main():
"""Define command configurations."""
parser = argparse.ArgumentParser(
prog="pymupdf",
description=mycenter("Basic PyMuPDF Functions"),
)
subps = parser.add_subparsers(
title="Subcommands", help="Enter 'command -h' for subcommand specific help"
)
# -------------------------------------------------------------------------
# 'show' command
# -------------------------------------------------------------------------
ps_show = subps.add_parser("show", description=mycenter("display PDF information"))
ps_show.add_argument("input", type=str, help="PDF filename")
ps_show.add_argument("-password", help="password")
ps_show.add_argument("-catalog", action="store_true", help="show PDF catalog")
ps_show.add_argument("-trailer", action="store_true", help="show PDF trailer")
ps_show.add_argument("-metadata", action="store_true", help="show PDF metadata")
ps_show.add_argument(
"-xrefs", type=str, help="show selected objects, format: 1,5-7,N"
)
ps_show.add_argument(
"-pages", type=str, help="show selected pages, format: 1,5-7,50-N"
)
ps_show.set_defaults(func=show)
# -------------------------------------------------------------------------
# 'clean' command
# -------------------------------------------------------------------------
ps_clean = subps.add_parser(
"clean", description=mycenter("optimize PDF, or create sub-PDF if pages given")
)
ps_clean.add_argument("input", type=str, help="PDF filename")
ps_clean.add_argument("output", type=str, help="output PDF filename")
ps_clean.add_argument("-password", help="password")
ps_clean.add_argument(
"-encryption",
help="encryption method",
choices=("keep", "none", "rc4-40", "rc4-128", "aes-128", "aes-256"),
default="none",
)
ps_clean.add_argument("-owner", type=str, help="owner password")
ps_clean.add_argument("-user", type=str, help="user password")
ps_clean.add_argument(
"-garbage",
type=int,
help="garbage collection level",
choices=range(5),
default=0,
)
ps_clean.add_argument(
"-compress",
action="store_true",
default=False,
help="compress (deflate) output",
)
ps_clean.add_argument(
"-ascii", action="store_true", default=False, help="ASCII encode binary data"
)
ps_clean.add_argument(
"-linear",
action="store_true",
default=False,
help="format for fast web display",
)
ps_clean.add_argument(
"-permission", type=int, default=-1, help="integer with permission levels"
)
ps_clean.add_argument(
"-sanitize",
action="store_true",
default=False,
help="sanitize / clean contents",
)
ps_clean.add_argument(
"-pretty", action="store_true", default=False, help="prettify PDF structure"
)
ps_clean.add_argument(
"-pages", help="output selected pages pages, format: 1,5-7,50-N"
)
ps_clean.set_defaults(func=clean)
# -------------------------------------------------------------------------
# 'join' command
# -------------------------------------------------------------------------
ps_join = subps.add_parser(
"join",
description=mycenter("join PDF documents"),
epilog="specify each input as 'filename[,password[,pages]]'",
)
ps_join.add_argument("input", nargs="*", help="input filenames")
ps_join.add_argument("-output", required=True, help="output filename")
ps_join.set_defaults(func=doc_join)
# -------------------------------------------------------------------------
# 'extract' command
# -------------------------------------------------------------------------
ps_extract = subps.add_parser(
"extract", description=mycenter("extract images and fonts to disk")
)
ps_extract.add_argument("input", type=str, help="PDF filename")
ps_extract.add_argument("-images", action="store_true", help="extract images")
ps_extract.add_argument("-fonts", action="store_true", help="extract fonts")
ps_extract.add_argument(
"-output", help="folder to receive output, defaults to current"
)
ps_extract.add_argument("-password", help="password")
ps_extract.add_argument(
"-pages", type=str, help="consider these pages only, format: 1,5-7,50-N"
)
ps_extract.set_defaults(func=extract_objects)
# -------------------------------------------------------------------------
# 'embed-info'
# -------------------------------------------------------------------------
ps_show = subps.add_parser(
"embed-info", description=mycenter("list embedded files")
)
ps_show.add_argument("input", help="PDF filename")
ps_show.add_argument("-name", help="if given, report only this one")
ps_show.add_argument("-detail", action="store_true", help="detail information")
ps_show.add_argument("-password", help="password")
ps_show.set_defaults(func=embedded_list)
# -------------------------------------------------------------------------
# 'embed-add' command
# -------------------------------------------------------------------------
ps_embed_add = subps.add_parser(
"embed-add", description=mycenter("add embedded file")
)
ps_embed_add.add_argument("input", help="PDF filename")
ps_embed_add.add_argument("-password", help="password")
ps_embed_add.add_argument(
"-output", help="output PDF filename, incremental save if none"
)
ps_embed_add.add_argument("-name", required=True, help="name of new entry")
ps_embed_add.add_argument("-path", required=True, help="path to data for new entry")
ps_embed_add.add_argument("-desc", help="description of new entry")
ps_embed_add.set_defaults(func=embedded_add)
# -------------------------------------------------------------------------
# 'embed-del' command
# -------------------------------------------------------------------------
ps_embed_del = subps.add_parser(
"embed-del", description=mycenter("delete embedded file")
)
ps_embed_del.add_argument("input", help="PDF filename")
ps_embed_del.add_argument("-password", help="password")
ps_embed_del.add_argument(
"-output", help="output PDF filename, incremental save if none"
)
ps_embed_del.add_argument("-name", required=True, help="name of entry to delete")
ps_embed_del.set_defaults(func=embedded_del)
# -------------------------------------------------------------------------
# 'embed-upd' command
# -------------------------------------------------------------------------
ps_embed_upd = subps.add_parser(
"embed-upd",
description=mycenter("update embedded file"),
epilog="except '-name' all parameters are optional",
)
ps_embed_upd.add_argument("input", help="PDF filename")
ps_embed_upd.add_argument("-name", required=True, help="name of entry")
ps_embed_upd.add_argument("-password", help="password")
ps_embed_upd.add_argument(
"-output", help="Output PDF filename, incremental save if none"
)
ps_embed_upd.add_argument("-path", help="path to new data for entry")
ps_embed_upd.add_argument("-filename", help="new filename to store in entry")
ps_embed_upd.add_argument(
"-ufilename", help="new unicode filename to store in entry"
)
ps_embed_upd.add_argument("-desc", help="new description to store in entry")
ps_embed_upd.set_defaults(func=embedded_upd)
# -------------------------------------------------------------------------
# 'embed-extract' command
# -------------------------------------------------------------------------
ps_embed_extract = subps.add_parser(
"embed-extract", description=mycenter("extract embedded file to disk")
)
ps_embed_extract.add_argument("input", type=str, help="PDF filename")
ps_embed_extract.add_argument("-name", required=True, help="name of entry")
ps_embed_extract.add_argument("-password", help="password")
ps_embed_extract.add_argument(
"-output", help="output filename, default is stored name"
)
ps_embed_extract.set_defaults(func=embedded_get)
# -------------------------------------------------------------------------
# 'embed-copy' command
# -------------------------------------------------------------------------
ps_embed_copy = subps.add_parser(
"embed-copy", description=mycenter("copy embedded files between PDFs")
)
ps_embed_copy.add_argument("input", type=str, help="PDF to receive embedded files")
ps_embed_copy.add_argument("-password", help="password of input")
ps_embed_copy.add_argument(
"-output", help="output PDF, incremental save to 'input' if omitted"
)
ps_embed_copy.add_argument(
"-source", required=True, help="copy embedded files from here"
)
ps_embed_copy.add_argument("-pwdsource", help="password of 'source' PDF")
ps_embed_copy.add_argument(
"-name", nargs="*", help="restrict copy to these entries"
)
ps_embed_copy.set_defaults(func=embedded_copy)
# -------------------------------------------------------------------------
# 'textlayout' command
# -------------------------------------------------------------------------
ps_gettext = subps.add_parser(
"gettext", description=mycenter("extract text in various formatting modes")
)
ps_gettext.add_argument("input", type=str, help="input document filename")
ps_gettext.add_argument("-password", help="password for input document")
ps_gettext.add_argument(
"-mode",
type=str,
help="mode: simple, block sort, or layout (default)",
choices=("simple", "blocks", "layout"),
default="layout",
)
ps_gettext.add_argument(
"-pages",
type=str,
help="select pages, format: 1,5-7,50-N",
default="1-N",
)
ps_gettext.add_argument(
"-noligatures",
action="store_true",
help="expand ligature characters (default False)",
default=False,
)
ps_gettext.add_argument(
"-convert-white",
action="store_true",
help="convert whitespace characters to white (default False)",
default=False,
)
ps_gettext.add_argument(
"-extra-spaces",
action="store_true",
help="fill gaps with spaces (default False)",
default=False,
)
ps_gettext.add_argument(
"-noformfeed",
action="store_true",
help="write linefeeds, no formfeeds (default False)",
default=False,
)
ps_gettext.add_argument(
"-skip-empty",
action="store_true",
help="suppress pages with no text (default False)",
default=False,
)
ps_gettext.add_argument(
"-output",
help="store text in this file (default inputfilename.txt)",
)
ps_gettext.add_argument(
"-grid",
type=float,
help="merge lines if closer than this (default 2)",
default=2,
)
ps_gettext.add_argument(
"-fontsize",
type=float,
help="only include text with a larger fontsize (default 3)",
default=3,
)
ps_gettext.set_defaults(func=gettext)
# -------------------------------------------------------------------------
# '_internal' command
# -------------------------------------------------------------------------
ps_internal = subps.add_parser(
"internal", description=mycenter("internal testing")
)
ps_internal.set_defaults(func=_internal)
# -------------------------------------------------------------------------
# start program
# -------------------------------------------------------------------------
args = parser.parse_args() # create parameter arguments class
if not hasattr(args, "func"): # no function selected
parser.print_help() # so print top level help
else:
args.func(args) # execute requested command
if __name__ == "__main__":
main()
| 41,110 | Python | .py | 1,028 | 31.143969 | 88 | 0.545941 | pymupdf/PyMuPDF | 5,009 | 480 | 32 | AGPL-3.0 | 9/5/2024, 5:12:54 PM (Europe/Amsterdam) |
21,297 | utils.py | pymupdf_PyMuPDF/src/utils.py | # ------------------------------------------------------------------------
# Copyright 2020-2022, Harald Lieder, mailto:harald.lieder@outlook.com
# License: GNU AFFERO GPL 3.0, https://www.gnu.org/licenses/agpl-3.0.html
#
# Part of "PyMuPDF", a Python binding for "MuPDF" (http://mupdf.com), a
# lightweight PDF, XPS, and E-book viewer, renderer and toolkit which is
# maintained and developed by Artifex Software, Inc. https://artifex.com.
# ------------------------------------------------------------------------
import io
import math
import os
import typing
import weakref
try:
from . import pymupdf
except Exception:
import pymupdf
try:
from . import mupdf
except Exception:
import mupdf
_format_g = pymupdf.format_g
g_exceptions_verbose = pymupdf.g_exceptions_verbose
TESSDATA_PREFIX = os.environ.get("TESSDATA_PREFIX")
point_like = "point_like"
rect_like = "rect_like"
matrix_like = "matrix_like"
quad_like = "quad_like"
AnyType = typing.Any
OptInt = typing.Union[int, None]
OptFloat = typing.Optional[float]
OptStr = typing.Optional[str]
OptDict = typing.Optional[dict]
OptBytes = typing.Optional[typing.ByteString]
OptSeq = typing.Optional[typing.Sequence]
"""
This is a collection of functions to extend PyMupdf.
"""
def write_text(
page: pymupdf.Page,
rect=None,
writers=None,
overlay=True,
color=None,
opacity=None,
keep_proportion=True,
rotate=0,
oc=0,
) -> None:
"""Write the text of one or more pymupdf.TextWriter objects.
Args:
rect: target rectangle. If None, the union of the text writers is used.
writers: one or more pymupdf.TextWriter objects.
overlay: put in foreground or background.
keep_proportion: maintain aspect ratio of rectangle sides.
rotate: arbitrary rotation angle.
oc: the xref of an optional content object
"""
assert isinstance(page, pymupdf.Page)
if not writers:
raise ValueError("need at least one pymupdf.TextWriter")
if type(writers) is pymupdf.TextWriter:
if rotate == 0 and rect is None:
writers.write_text(page, opacity=opacity, color=color, overlay=overlay)
return None
else:
writers = (writers,)
clip = writers[0].text_rect
textdoc = pymupdf.Document()
tpage = textdoc.new_page(width=page.rect.width, height=page.rect.height)
for writer in writers:
clip |= writer.text_rect
writer.write_text(tpage, opacity=opacity, color=color)
if rect is None:
rect = clip
page.show_pdf_page(
rect,
textdoc,
0,
overlay=overlay,
keep_proportion=keep_proportion,
rotate=rotate,
clip=clip,
oc=oc,
)
textdoc = None
tpage = None
def show_pdf_page(
page,
rect,
src,
pno=0,
keep_proportion=True,
overlay=True,
oc=0,
rotate=0,
clip=None,
) -> int:
"""Show page number 'pno' of PDF 'src' in rectangle 'rect'.
Args:
rect: (rect-like) where to place the source image
src: (document) source PDF
pno: (int) source page number
keep_proportion: (bool) do not change width-height-ratio
overlay: (bool) put in foreground
oc: (xref) make visibility dependent on this OCG / OCMD (which must be defined in the target PDF)
rotate: (int) degrees (multiple of 90)
clip: (rect-like) part of source page rectangle
Returns:
xref of inserted object (for reuse)
"""
def calc_matrix(sr, tr, keep=True, rotate=0):
"""Calculate transformation matrix from source to target rect.
Notes:
The product of four matrices in this sequence: (1) translate correct
source corner to origin, (2) rotate, (3) scale, (4) translate to
target's top-left corner.
Args:
sr: source rect in PDF (!) coordinate system
tr: target rect in PDF coordinate system
keep: whether to keep source ratio of width to height
rotate: rotation angle in degrees
Returns:
Transformation matrix.
"""
# calc center point of source rect
smp = (sr.tl + sr.br) / 2.0
# calc center point of target rect
tmp = (tr.tl + tr.br) / 2.0
# m moves to (0, 0), then rotates
m = pymupdf.Matrix(1, 0, 0, 1, -smp.x, -smp.y) * pymupdf.Matrix(rotate)
sr1 = sr * m # resulting source rect to calculate scale factors
fw = tr.width / sr1.width # scale the width
fh = tr.height / sr1.height # scale the height
if keep:
fw = fh = min(fw, fh) # take min if keeping aspect ratio
m *= pymupdf.Matrix(fw, fh) # concat scale matrix
m *= pymupdf.Matrix(1, 0, 0, 1, tmp.x, tmp.y) # concat move to target center
return pymupdf.JM_TUPLE(m)
pymupdf.CheckParent(page)
doc = page.parent
if not doc.is_pdf or not src.is_pdf:
raise ValueError("is no PDF")
if rect.is_empty or rect.is_infinite:
raise ValueError("rect must be finite and not empty")
while pno < 0: # support negative page numbers
pno += src.page_count
src_page = src[pno] # load source page
if src_page.get_contents() == []:
raise ValueError("nothing to show - source page empty")
tar_rect = rect * ~page.transformation_matrix # target rect in PDF coordinates
src_rect = src_page.rect if not clip else src_page.rect & clip # source rect
if src_rect.is_empty or src_rect.is_infinite:
raise ValueError("clip must be finite and not empty")
src_rect = src_rect * ~src_page.transformation_matrix # ... in PDF coord
matrix = calc_matrix(src_rect, tar_rect, keep=keep_proportion, rotate=rotate)
# list of existing /Form /XObjects
ilst = [i[1] for i in doc.get_page_xobjects(page.number)]
ilst += [i[7] for i in doc.get_page_images(page.number)]
ilst += [i[4] for i in doc.get_page_fonts(page.number)]
# create a name not in that list
n = "fzFrm"
i = 0
_imgname = n + "0"
while _imgname in ilst:
i += 1
_imgname = n + str(i)
isrc = src._graft_id # used as key for graftmaps
if doc._graft_id == isrc:
raise ValueError("source document must not equal target")
# retrieve / make pymupdf.Graftmap for source PDF
gmap = doc.Graftmaps.get(isrc, None)
if gmap is None:
gmap = pymupdf.Graftmap(doc)
doc.Graftmaps[isrc] = gmap
# take note of generated xref for automatic reuse
pno_id = (isrc, pno) # id of src[pno]
xref = doc.ShownPages.get(pno_id, 0)
if overlay:
page.wrap_contents() # ensure a balanced graphics state
xref = page._show_pdf_page(
src_page,
overlay=overlay,
matrix=matrix,
xref=xref,
oc=oc,
clip=src_rect,
graftmap=gmap,
_imgname=_imgname,
)
doc.ShownPages[pno_id] = xref
return xref
def replace_image(page: pymupdf.Page, xref: int, *, filename=None, pixmap=None, stream=None):
"""Replace the image referred to by xref.
Replace the image by changing the object definition stored under xref. This
will leave the pages appearance instructions intact, so the new image is
being displayed with the same bbox, rotation etc.
By providing a small fully transparent image, an effect as if the image had
been deleted can be achieved.
A typical use may include replacing large images by a smaller version,
e.g. with a lower resolution or graylevel instead of colored.
Args:
xref: the xref of the image to replace.
filename, pixmap, stream: exactly one of these must be provided. The
meaning being the same as in Page.insert_image.
"""
doc = page.parent # the owning document
if not doc.xref_is_image(xref):
raise ValueError("xref not an image") # insert new image anywhere in page
if bool(filename) + bool(stream) + bool(pixmap) != 1:
raise ValueError("Exactly one of filename/stream/pixmap must be given")
new_xref = page.insert_image(
page.rect, filename=filename, stream=stream, pixmap=pixmap
)
doc.xref_copy(new_xref, xref) # copy over new to old
last_contents_xref = page.get_contents()[-1]
# new image insertion has created a new /Contents source,
# which we will set to spaces now
doc.update_stream(last_contents_xref, b" ")
def delete_image(page: pymupdf.Page, xref: int):
"""Delete the image referred to by xef.
Actually replaces by a small transparent Pixmap using method Page.replace_image.
Args:
xref: xref of the image to delete.
"""
# make a small 100% transparent pixmap (of just any dimension)
pix = pymupdf.Pixmap(pymupdf.csGRAY, (0, 0, 1, 1), 1)
pix.clear_with() # clear all samples bytes to 0x00
page.replace_image(xref, pixmap=pix)
def insert_image(
page,
rect,
*,
alpha=-1,
filename=None,
height=0,
keep_proportion=True,
mask=None,
oc=0,
overlay=True,
pixmap=None,
rotate=0,
stream=None,
width=0,
xref=0,
):
"""Insert an image for display in a rectangle.
Args:
rect: (rect_like) position of image on the page.
alpha: (int, optional) set to 0 if image has no transparency.
filename: (str, Path, file object) image filename.
height: (int)
keep_proportion: (bool) keep width / height ratio (default).
mask: (bytes, optional) image consisting of alpha values to use.
oc: (int) xref of OCG or OCMD to declare as Optional Content.
overlay: (bool) put in foreground (default) or background.
pixmap: (pymupdf.Pixmap) use this as image.
rotate: (int) rotate by 0, 90, 180 or 270 degrees.
stream: (bytes) use this as image.
width: (int)
xref: (int) use this as image.
'page' and 'rect' are positional, all other parameters are keywords.
If 'xref' is given, that image is used. Other input options are ignored.
Else, exactly one of pixmap, stream or filename must be given.
'alpha=0' for non-transparent images improves performance significantly.
Affects stream and filename only.
Optimum transparent insertions are possible by using filename / stream in
conjunction with a 'mask' image of alpha values.
Returns:
xref (int) of inserted image. Re-use as argument for multiple insertions.
"""
pymupdf.CheckParent(page)
doc = page.parent
if not doc.is_pdf:
raise ValueError("is no PDF")
if xref == 0 and (bool(filename) + bool(stream) + bool(pixmap) != 1):
raise ValueError("xref=0 needs exactly one of filename, pixmap, stream")
if filename:
if type(filename) is str:
pass
elif hasattr(filename, "absolute"):
filename = str(filename)
elif hasattr(filename, "name"):
filename = filename.name
else:
raise ValueError("bad filename")
if filename and not os.path.exists(filename):
raise FileNotFoundError("No such file: '%s'" % filename)
elif stream and type(stream) not in (bytes, bytearray, io.BytesIO):
raise ValueError("stream must be bytes-like / BytesIO")
elif pixmap and type(pixmap) is not pymupdf.Pixmap:
raise ValueError("pixmap must be a pymupdf.Pixmap")
if mask and not (stream or filename):
raise ValueError("mask requires stream or filename")
if mask and type(mask) not in (bytes, bytearray, io.BytesIO):
raise ValueError("mask must be bytes-like / BytesIO")
while rotate < 0:
rotate += 360
while rotate >= 360:
rotate -= 360
if rotate not in (0, 90, 180, 270):
raise ValueError("bad rotate value")
r = pymupdf.Rect(rect)
if r.is_empty or r.is_infinite:
raise ValueError("rect must be finite and not empty")
clip = r * ~page.transformation_matrix
# Create a unique image reference name.
ilst = [i[7] for i in doc.get_page_images(page.number)]
ilst += [i[1] for i in doc.get_page_xobjects(page.number)]
ilst += [i[4] for i in doc.get_page_fonts(page.number)]
n = "fzImg" # 'pymupdf image'
i = 0
_imgname = n + "0" # first name candidate
while _imgname in ilst:
i += 1
_imgname = n + str(i) # try new name
if overlay:
page.wrap_contents() # ensure a balanced graphics state
digests = doc.InsertedImages
xref, digests = page._insert_image(
filename=filename,
pixmap=pixmap,
stream=stream,
imask=mask,
clip=clip,
overlay=overlay,
oc=oc,
xref=xref,
rotate=rotate,
keep_proportion=keep_proportion,
width=width,
height=height,
alpha=alpha,
_imgname=_imgname,
digests=digests,
)
if digests is not None:
doc.InsertedImages = digests
return xref
def search_for(
page,
text,
*,
clip=None,
quads=False,
flags=pymupdf.TEXT_DEHYPHENATE
| pymupdf.TEXT_PRESERVE_WHITESPACE
| pymupdf.TEXT_PRESERVE_LIGATURES
| pymupdf.TEXT_MEDIABOX_CLIP
,
textpage=None,
) -> list:
"""Search for a string on a page.
Args:
text: string to be searched for
clip: restrict search to this rectangle
quads: (bool) return quads instead of rectangles
flags: bit switches, default: join hyphened words
textpage: a pre-created pymupdf.TextPage
Returns:
a list of rectangles or quads, each containing one occurrence.
"""
if clip is not None:
clip = pymupdf.Rect(clip)
pymupdf.CheckParent(page)
tp = textpage
if tp is None:
tp = page.get_textpage(clip=clip, flags=flags) # create pymupdf.TextPage
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
rlist = tp.search(text, quads=quads)
if textpage is None:
del tp
return rlist
def search_page_for(
doc: pymupdf.Document,
pno: int,
text: str,
quads: bool = False,
clip: rect_like = None,
flags: int = pymupdf.TEXT_DEHYPHENATE
| pymupdf.TEXT_PRESERVE_LIGATURES
| pymupdf.TEXT_PRESERVE_WHITESPACE
| pymupdf.TEXT_MEDIABOX_CLIP
,
textpage: pymupdf.TextPage = None,
) -> list:
"""Search for a string on a page.
Args:
pno: page number
text: string to be searched for
clip: restrict search to this rectangle
quads: (bool) return quads instead of rectangles
flags: bit switches, default: join hyphened words
textpage: reuse a prepared textpage
Returns:
a list of rectangles or quads, each containing an occurrence.
"""
return doc[pno].search_for(
text,
quads=quads,
clip=clip,
flags=flags,
textpage=textpage,
)
def get_text_blocks(
page: pymupdf.Page,
clip: rect_like = None,
flags: OptInt = None,
textpage: pymupdf.TextPage = None,
sort: bool = False,
) -> list:
"""Return the text blocks on a page.
Notes:
Lines in a block are concatenated with line breaks.
Args:
flags: (int) control the amount of data parsed into the textpage.
Returns:
A list of the blocks. Each item contains the containing rectangle
coordinates, text lines, running block number and block type.
"""
pymupdf.CheckParent(page)
if flags is None:
flags = pymupdf.TEXTFLAGS_BLOCKS
tp = textpage
if tp is None:
tp = page.get_textpage(clip=clip, flags=flags)
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
blocks = tp.extractBLOCKS()
if textpage is None:
del tp
if sort is True:
blocks.sort(key=lambda b: (b[3], b[0]))
return blocks
def get_text_words(
page: pymupdf.Page,
clip: rect_like = None,
flags: OptInt = None,
textpage: pymupdf.TextPage = None,
sort: bool = False,
delimiters=None,
tolerance=3,
) -> list:
"""Return the text words as a list with the bbox for each word.
Args:
page: pymupdf.Page
clip: (rect-like) area on page to consider
flags: (int) control the amount of data parsed into the textpage.
textpage: (pymupdf.TextPage) either passed-in or None.
sort: (bool) sort the words in reading sequence.
delimiters: (str,list) characters to use as word delimiters.
tolerance: (float) consider words to be part of the same line if
top or bottom coordinate are not larger than this. Relevant
only if sort=True.
Returns:
Word tuples (x0, y0, x1, y1, "word", bno, lno, wno).
"""
def sort_words(words):
"""Sort words line-wise, forgiving small deviations."""
words.sort(key=lambda w: (w[3], w[0]))
nwords = [] # final word list
line = [words[0]] # collects words roughly in same line
lrect = pymupdf.Rect(words[0][:4]) # start the line rectangle
for w in words[1:]:
wrect = pymupdf.Rect(w[:4])
if (
abs(wrect.y0 - lrect.y0) <= tolerance
or abs(wrect.y1 - lrect.y1) <= tolerance
):
line.append(w)
lrect |= wrect
else:
line.sort(key=lambda w: w[0]) # sort words in line l-t-r
nwords.extend(line) # append to final words list
line = [w] # start next line
lrect = wrect # start next line rect
line.sort(key=lambda w: w[0]) # sort words in line l-t-r
nwords.extend(line) # append to final words list
return nwords
pymupdf.CheckParent(page)
if flags is None:
flags = pymupdf.TEXTFLAGS_WORDS
tp = textpage
if tp is None:
tp = page.get_textpage(clip=clip, flags=flags)
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
words = tp.extractWORDS(delimiters)
# if textpage was given, we subselect the words in clip
if textpage is not None and clip is not None:
# sub-select words contained in clip
clip = pymupdf.Rect(clip)
words = [
w for w in words if abs(clip & w[:4]) >= 0.5 * abs(pymupdf.Rect(w[:4]))
]
if textpage is None:
del tp
if words and sort is True:
# advanced sort if any words found
words = sort_words(words)
return words
def get_sorted_text(
page: pymupdf.Page,
clip: rect_like = None,
flags: OptInt = None,
textpage: pymupdf.TextPage = None,
tolerance=3,
) -> str:
"""Extract plain text avoiding unacceptable line breaks.
Text contained in clip will be sorted in reading sequence. Some effort
is also spent to simulate layout vertically and horizontally.
Args:
page: pymupdf.Page
clip: (rect-like) only consider text inside
flags: (int) text extraction flags
textpage: pymupdf.TextPage
tolerance: (float) consider words to be on the same line if their top
or bottom coordinates do not differ more than this.
Notes:
If a TextPage is provided, all text is checked for being inside clip
with at least 50% of its bbox.
This allows to use some "global" TextPage in conjunction with sub-
selecting words in parts of the defined TextPage rectangle.
Returns:
A text string in reading sequence. Left indentation of each line,
inter-line and inter-word distances strive to reflect the layout.
"""
def line_text(clip, line):
"""Create the string of one text line.
We are trying to simulate some horizontal layout here, too.
Args:
clip: (pymupdf.Rect) the area from which all text is being read.
line: (list) word tuples (rect, text) contained in the line
Returns:
Text in this line. Generated from words in 'line'. Distance from
predecessor is translated to multiple spaces, thus simulating
text indentations and large horizontal distances.
"""
line.sort(key=lambda w: w[0].x0)
ltext = "" # text in the line
x1 = clip.x0 # end coordinate of ltext
lrect = pymupdf.EMPTY_RECT() # bbox of this line
for r, t in line:
lrect |= r # update line bbox
# convert distance to previous word to multiple spaces
dist = max(
int(round((r.x0 - x1) / r.width * len(t))),
0 if x1 == clip.x0 else 1,
) # number of space characters
ltext += " " * dist + t # append word string
x1 = r.x1 # update new end position
return ltext
# Extract words in correct sequence first.
words = [
(pymupdf.Rect(w[:4]), w[4])
for w in get_text_words(
page,
clip=clip,
flags=flags,
textpage=textpage,
sort=True,
tolerance=tolerance,
)
]
if not words: # no text present
return ""
totalbox = pymupdf.EMPTY_RECT() # area covering all text
for wr, text in words:
totalbox |= wr
lines = [] # list of reconstituted lines
line = [words[0]] # current line
lrect = words[0][0] # the line's rectangle
# walk through the words
for wr, text in words[1:]: # start with second word
w0r, _ = line[-1] # read previous word in current line
# if this word matches top or bottom of the line, append it
if abs(lrect.y0 - wr.y0) <= tolerance or abs(lrect.y1 - wr.y1) <= tolerance:
line.append((wr, text))
lrect |= wr
else:
# output current line and re-initialize
ltext = line_text(totalbox, line)
lines.append((lrect, ltext))
line = [(wr, text)]
lrect = wr
# also append unfinished last line
ltext = line_text(totalbox, line)
lines.append((lrect, ltext))
# sort all lines vertically
lines.sort(key=lambda l: (l[0].y1))
text = lines[0][1] # text of first line
y1 = lines[0][0].y1 # its bottom coordinate
for lrect, ltext in lines[1:]:
distance = min(int(round((lrect.y0 - y1) / lrect.height)), 5)
breaks = "\n" * (distance + 1)
text += breaks + ltext
y1 = lrect.y1
# return text in clip
return text
def get_textbox(
page: pymupdf.Page,
rect: rect_like,
textpage: pymupdf.TextPage = None,
) -> str:
tp = textpage
if tp is None:
tp = page.get_textpage()
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
rc = tp.extractTextbox(rect)
if textpage is None:
del tp
return rc
def get_text_selection(
page: pymupdf.Page,
p1: point_like,
p2: point_like,
clip: rect_like = None,
textpage: pymupdf.TextPage = None,
):
pymupdf.CheckParent(page)
tp = textpage
if tp is None:
tp = page.get_textpage(clip=clip, flags=pymupdf.TEXT_DEHYPHENATE)
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
rc = tp.extractSelection(p1, p2)
if textpage is None:
del tp
return rc
def get_textpage_ocr(
page: pymupdf.Page,
flags: int = 0,
language: str = "eng",
dpi: int = 72,
full: bool = False,
tessdata: str = None,
) -> pymupdf.TextPage:
"""Create a Textpage from combined results of normal and OCR text parsing.
Args:
flags: (int) control content becoming part of the result.
language: (str) specify expected language(s). Default is "eng" (English).
dpi: (int) resolution in dpi, default 72.
full: (bool) whether to OCR the full page image, or only its images (default)
"""
pymupdf.CheckParent(page)
if not TESSDATA_PREFIX and not tessdata:
raise RuntimeError("No OCR support: TESSDATA_PREFIX not set")
def full_ocr(page, dpi, language, flags):
zoom = dpi / 72
mat = pymupdf.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat)
ocr_pdf = pymupdf.Document(
"pdf",
pix.pdfocr_tobytes(
compress=False,
language=language,
tessdata=tessdata,
),
)
ocr_page = ocr_pdf.load_page(0)
unzoom = page.rect.width / ocr_page.rect.width
ctm = pymupdf.Matrix(unzoom, unzoom) * page.derotation_matrix
tpage = ocr_page.get_textpage(flags=flags, matrix=ctm)
ocr_pdf.close()
pix = None
tpage.parent = weakref.proxy(page)
return tpage
# if OCR for the full page, OCR its pixmap @ desired dpi
if full is True:
return full_ocr(page, dpi, language, flags)
# For partial OCR, make a normal textpage, then extend it with text that
# is OCRed from each image.
# Because of this, we need the images flag bit set ON.
tpage = page.get_textpage(flags=flags)
for block in page.get_text("dict", flags=pymupdf.TEXT_PRESERVE_IMAGES)["blocks"]:
if block["type"] != 1: # only look at images
continue
bbox = pymupdf.Rect(block["bbox"])
if bbox.width <= 3 or bbox.height <= 3: # ignore tiny stuff
continue
exception_types = (RuntimeError, mupdf.FzErrorBase)
if pymupdf.mupdf_version_tuple < (1, 24):
exception_types = RuntimeError
try:
pix = pymupdf.Pixmap(block["image"]) # get image pixmap
if pix.n - pix.alpha != 3: # we need to convert this to RGB!
pix = pymupdf.Pixmap(pymupdf.csRGB, pix)
if pix.alpha: # must remove alpha channel
pix = pymupdf.Pixmap(pix, 0)
imgdoc = pymupdf.Document(
"pdf",
pix.pdfocr_tobytes(language=language, tessdata=tessdata),
) # pdf with OCRed page
imgpage = imgdoc.load_page(0) # read image as a page
pix = None
# compute matrix to transform coordinates back to that of 'page'
imgrect = imgpage.rect # page size of image PDF
shrink = pymupdf.Matrix(1 / imgrect.width, 1 / imgrect.height)
mat = shrink * block["transform"]
imgpage.extend_textpage(tpage, flags=0, matrix=mat)
imgdoc.close()
except exception_types:
if g_exceptions_verbose: pymupdf.exception_info()
tpage = None
pymupdf.message("Falling back to full page OCR")
return full_ocr(page, dpi, language, flags)
return tpage
def get_image_info(page: pymupdf.Page, hashes: bool = False, xrefs: bool = False) -> list:
"""Extract image information only from a pymupdf.TextPage.
Args:
hashes: (bool) include MD5 hash for each image.
xrefs: (bool) try to find the xref for each image. Sets hashes to true.
"""
doc = page.parent
if xrefs and doc.is_pdf:
hashes = True
if not doc.is_pdf:
xrefs = False
imginfo = getattr(page, "_image_info", None)
if imginfo and not xrefs:
return imginfo
if not imginfo:
tp = page.get_textpage(flags=pymupdf.TEXT_PRESERVE_IMAGES)
imginfo = tp.extractIMGINFO(hashes=hashes)
del tp
if hashes:
page._image_info = imginfo
if not xrefs or not doc.is_pdf:
return imginfo
imglist = page.get_images()
digests = {}
for item in imglist:
xref = item[0]
pix = pymupdf.Pixmap(doc, xref)
digests[pix.digest] = xref
del pix
for i in range(len(imginfo)):
item = imginfo[i]
xref = digests.get(item["digest"], 0)
item["xref"] = xref
imginfo[i] = item
return imginfo
def get_image_rects(page: pymupdf.Page, name, transform=False) -> list:
"""Return list of image positions on a page.
Args:
name: (str, list, int) image identification. May be reference name, an
item of the page's image list or an xref.
transform: (bool) whether to also return the transformation matrix.
Returns:
A list of pymupdf.Rect objects or tuples of (pymupdf.Rect, pymupdf.Matrix)
for all image locations on the page.
"""
if type(name) in (list, tuple):
xref = name[0]
elif type(name) is int:
xref = name
else:
imglist = [i for i in page.get_images() if i[7] == name]
if imglist == []:
raise ValueError("bad image name")
elif len(imglist) != 1:
raise ValueError("multiple image names found")
xref = imglist[0][0]
pix = pymupdf.Pixmap(page.parent, xref) # make pixmap of the image to compute MD5
digest = pix.digest
del pix
infos = page.get_image_info(hashes=True)
if not transform:
bboxes = [pymupdf.Rect(im["bbox"]) for im in infos if im["digest"] == digest]
else:
bboxes = [
(pymupdf.Rect(im["bbox"]), pymupdf.Matrix(im["transform"]))
for im in infos
if im["digest"] == digest
]
return bboxes
def get_text(
page: pymupdf.Page,
option: str = "text",
clip: rect_like = None,
flags: OptInt = None,
textpage: pymupdf.TextPage = None,
sort: bool = False,
delimiters=None,
tolerance=3,
):
"""Extract text from a page or an annotation.
This is a unifying wrapper for various methods of the pymupdf.TextPage class.
Args:
option: (str) text, words, blocks, html, dict, json, rawdict, xhtml or xml.
clip: (rect-like) restrict output to this area.
flags: bit switches to e.g. exclude images or decompose ligatures.
textpage: reuse this pymupdf.TextPage and make no new one. If specified,
'flags' and 'clip' are ignored.
Returns:
the output of methods get_text_words / get_text_blocks or pymupdf.TextPage
methods extractText, extractHTML, extractDICT, extractJSON, extractRAWDICT,
extractXHTML or etractXML respectively.
Default and misspelling choice is "text".
"""
formats = {
"text": pymupdf.TEXTFLAGS_TEXT,
"html": pymupdf.TEXTFLAGS_HTML,
"json": pymupdf.TEXTFLAGS_DICT,
"rawjson": pymupdf.TEXTFLAGS_RAWDICT,
"xml": pymupdf.TEXTFLAGS_XML,
"xhtml": pymupdf.TEXTFLAGS_XHTML,
"dict": pymupdf.TEXTFLAGS_DICT,
"rawdict": pymupdf.TEXTFLAGS_RAWDICT,
"words": pymupdf.TEXTFLAGS_WORDS,
"blocks": pymupdf.TEXTFLAGS_BLOCKS,
}
option = option.lower()
if option not in formats:
option = "text"
if flags is None:
flags = formats[option]
if option == "words":
return get_text_words(
page,
clip=clip,
flags=flags,
textpage=textpage,
sort=sort,
delimiters=delimiters,
)
if option == "blocks":
return get_text_blocks(
page, clip=clip, flags=flags, textpage=textpage, sort=sort
)
if option == "text" and sort is True:
return get_sorted_text(
page,
clip=clip,
flags=flags,
textpage=textpage,
tolerance=tolerance,
)
pymupdf.CheckParent(page)
cb = None
if option in ("html", "xml", "xhtml"): # no clipping for MuPDF functions
clip = page.cropbox
if clip is not None:
clip = pymupdf.Rect(clip)
cb = None
elif type(page) is pymupdf.Page:
cb = page.cropbox
# pymupdf.TextPage with or without images
tp = textpage
#pymupdf.exception_info()
if tp is None:
tp = page.get_textpage(clip=clip, flags=flags)
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
#pymupdf.log( '{option=}')
if option == "json":
t = tp.extractJSON(cb=cb, sort=sort)
elif option == "rawjson":
t = tp.extractRAWJSON(cb=cb, sort=sort)
elif option == "dict":
t = tp.extractDICT(cb=cb, sort=sort)
elif option == "rawdict":
t = tp.extractRAWDICT(cb=cb, sort=sort)
elif option == "html":
t = tp.extractHTML()
elif option == "xml":
t = tp.extractXML()
elif option == "xhtml":
t = tp.extractXHTML()
else:
t = tp.extractText(sort=sort)
if textpage is None:
del tp
return t
def get_page_text(
doc: pymupdf.Document,
pno: int,
option: str = "text",
clip: rect_like = None,
flags: OptInt = None,
textpage: pymupdf.TextPage = None,
sort: bool = False,
) -> typing.Any:
"""Extract a document page's text by page number.
Notes:
Convenience function calling page.get_text().
Args:
pno: page number
option: (str) text, words, blocks, html, dict, json, rawdict, xhtml or xml.
Returns:
output from page.TextPage().
"""
return doc[pno].get_text(option, clip=clip, flags=flags, sort=sort)
def get_pixmap(
page: pymupdf.Page,
*,
matrix: matrix_like=pymupdf.Identity,
dpi=None,
colorspace: pymupdf.Colorspace=pymupdf.csRGB,
clip: rect_like=None,
alpha: bool=False,
annots: bool=True,
) -> pymupdf.Pixmap:
"""Create pixmap of page.
Keyword args:
matrix: Matrix for transformation (default: Identity).
dpi: desired dots per inch. If given, matrix is ignored.
colorspace: (str/Colorspace) cmyk, rgb, gray - case ignored, default csRGB.
clip: (irect-like) restrict rendering to this area.
alpha: (bool) whether to include alpha channel
annots: (bool) whether to also render annotations
"""
if dpi:
zoom = dpi / 72
matrix = pymupdf.Matrix(zoom, zoom)
if type(colorspace) is str:
if colorspace.upper() == "GRAY":
colorspace = pymupdf.csGRAY
elif colorspace.upper() == "CMYK":
colorspace = pymupdf.csCMYK
else:
colorspace = pymupdf.csRGB
if colorspace.n not in (1, 3, 4):
raise ValueError("unsupported colorspace")
dl = page.get_displaylist(annots=annots)
pix = dl.get_pixmap(matrix=matrix, colorspace=colorspace, alpha=alpha, clip=clip)
dl = None
if dpi:
pix.set_dpi(dpi, dpi)
return pix
def get_page_pixmap(
doc: pymupdf.Document,
pno: int,
*,
matrix: matrix_like = pymupdf.Identity,
dpi=None,
colorspace: pymupdf.Colorspace = pymupdf.csRGB,
clip: rect_like = None,
alpha: bool = False,
annots: bool = True,
) -> pymupdf.Pixmap:
"""Create pixmap of document page by page number.
Notes:
Convenience function calling page.get_pixmap.
Args:
pno: (int) page number
matrix: pymupdf.Matrix for transformation (default: pymupdf.Identity).
colorspace: (str,pymupdf.Colorspace) rgb, rgb, gray - case ignored, default csRGB.
clip: (irect-like) restrict rendering to this area.
alpha: (bool) include alpha channel
annots: (bool) also render annotations
"""
return doc[pno].get_pixmap(
matrix=matrix,
dpi=dpi, colorspace=colorspace,
clip=clip,
alpha=alpha,
annots=annots
)
def getLinkDict(ln, document=None) -> dict:
if isinstance(ln, pymupdf.Outline):
dest = ln.destination(document)
elif isinstance(ln, pymupdf.Link):
dest = ln.dest
else:
assert 0, f'Unexpected {type(ln)=}.'
nl = {"kind": dest.kind, "xref": 0}
try:
if hasattr(ln, 'rect'):
nl["from"] = ln.rect
except Exception:
# This seems to happen quite often in PyMuPDF/tests.
if g_exceptions_verbose >= 2: pymupdf.exception_info()
pass
pnt = pymupdf.Point(0, 0)
if dest.flags & pymupdf.LINK_FLAG_L_VALID:
pnt.x = dest.lt.x
if dest.flags & pymupdf.LINK_FLAG_T_VALID:
pnt.y = dest.lt.y
if dest.kind == pymupdf.LINK_URI:
nl["uri"] = dest.uri
elif dest.kind == pymupdf.LINK_GOTO:
nl["page"] = dest.page
nl["to"] = pnt
if dest.flags & pymupdf.LINK_FLAG_R_IS_ZOOM:
nl["zoom"] = dest.rb.x
else:
nl["zoom"] = 0.0
elif dest.kind == pymupdf.LINK_GOTOR:
nl["file"] = dest.file_spec.replace("\\", "/")
nl["page"] = dest.page
if dest.page < 0:
nl["to"] = dest.dest
else:
nl["to"] = pnt
if dest.flags & pymupdf.LINK_FLAG_R_IS_ZOOM:
nl["zoom"] = dest.rb.x
else:
nl["zoom"] = 0.0
elif dest.kind == pymupdf.LINK_LAUNCH:
nl["file"] = dest.file_spec.replace("\\", "/")
elif dest.kind == pymupdf.LINK_NAMED:
# The dicts should not have same key(s).
assert not (dest.named.keys() & nl.keys())
nl.update(dest.named)
if 'to' in nl:
nl['to'] = pymupdf.Point(nl['to'])
else:
nl["page"] = dest.page
return nl
def get_links(page: pymupdf.Page) -> list:
"""Create a list of all links contained in a PDF page.
Notes:
see PyMuPDF ducmentation for details.
"""
pymupdf.CheckParent(page)
ln = page.first_link
links = []
while ln:
nl = getLinkDict(ln, page.parent)
links.append(nl)
ln = ln.next
if links != [] and page.parent.is_pdf:
linkxrefs = [x for x in
#page.annot_xrefs()
pymupdf.JM_get_annot_xref_list2(page)
if x[1] == pymupdf.PDF_ANNOT_LINK # pylint: disable=no-member
]
if len(linkxrefs) == len(links):
for i in range(len(linkxrefs)):
links[i]["xref"] = linkxrefs[i][0]
links[i]["id"] = linkxrefs[i][2]
return links
def get_toc(
doc: pymupdf.Document,
simple: bool = True,
) -> list:
"""Create a table of contents.
Args:
simple: a bool to control output. Returns a list, where each entry consists of outline level, title, page number and link destination (if simple = False). For details see PyMuPDF's documentation.
"""
def recurse(olItem, liste, lvl):
"""Recursively follow the outline item chain and record item information in a list."""
while olItem and olItem.this.m_internal:
if olItem.title:
title = olItem.title
else:
title = " "
if not olItem.is_external:
if olItem.uri:
if olItem.page == -1:
resolve = doc.resolve_link(olItem.uri)
page = resolve[0] + 1
else:
page = olItem.page + 1
else:
page = -1
else:
page = -1
if not simple:
link = getLinkDict(olItem, doc)
liste.append([lvl, title, page, link])
else:
liste.append([lvl, title, page])
if olItem.down:
liste = recurse(olItem.down, liste, lvl + 1)
olItem = olItem.next
return liste
# ensure document is open
if doc.is_closed:
raise ValueError("document closed")
doc.init_doc()
olItem = doc.outline
if not olItem:
return []
lvl = 1
liste = []
toc = recurse(olItem, liste, lvl)
if doc.is_pdf and simple is False:
doc._extend_toc_items(toc)
return toc
def del_toc_item(
doc: pymupdf.Document,
idx: int,
) -> None:
"""Delete TOC / bookmark item by index."""
xref = doc.get_outline_xrefs()[idx]
doc._remove_toc_item(xref)
def set_toc_item(
doc: pymupdf.Document,
idx: int,
dest_dict: OptDict = None,
kind: OptInt = None,
pno: OptInt = None,
uri: OptStr = None,
title: OptStr = None,
to: point_like = None,
filename: OptStr = None,
zoom: float = 0,
) -> None:
"""Update TOC item by index.
It allows changing the item's title and link destination.
Args:
idx:
(int) desired index of the TOC list, as created by get_toc.
dest_dict:
(dict) destination dictionary as created by get_toc(False).
Outrules all other parameters. If None, the remaining parameters
are used to make a dest dictionary.
kind:
(int) kind of link (pymupdf.LINK_GOTO, etc.). If None, then only
the title will be updated. If pymupdf.LINK_NONE, the TOC item will
be deleted.
pno:
(int) page number (1-based like in get_toc). Required if
pymupdf.LINK_GOTO.
uri:
(str) the URL, required if pymupdf.LINK_URI.
title:
(str) the new title. No change if None.
to:
(point-like) destination on the target page. If omitted, (72, 36)
will be used as target coordinates.
filename:
(str) destination filename, required for pymupdf.LINK_GOTOR and
pymupdf.LINK_LAUNCH.
name:
(str) a destination name for pymupdf.LINK_NAMED.
zoom:
(float) a zoom factor for the target location (pymupdf.LINK_GOTO).
"""
xref = doc.get_outline_xrefs()[idx]
page_xref = 0
if type(dest_dict) is dict:
if dest_dict["kind"] == pymupdf.LINK_GOTO:
pno = dest_dict["page"]
page_xref = doc.page_xref(pno)
page_height = doc.page_cropbox(pno).height
to = dest_dict.get('to', pymupdf.Point(72, 36))
to.y = page_height - to.y
dest_dict["to"] = to
action = getDestStr(page_xref, dest_dict)
if not action.startswith("/A"):
raise ValueError("bad bookmark dest")
color = dest_dict.get("color")
if color:
color = list(map(float, color))
if len(color) != 3 or min(color) < 0 or max(color) > 1:
raise ValueError("bad color value")
bold = dest_dict.get("bold", False)
italic = dest_dict.get("italic", False)
flags = italic + 2 * bold
collapse = dest_dict.get("collapse")
return doc._update_toc_item(
xref,
action=action[2:],
title=title,
color=color,
flags=flags,
collapse=collapse,
)
if kind == pymupdf.LINK_NONE: # delete bookmark item
return doc.del_toc_item(idx)
if kind is None and title is None: # treat as no-op
return None
if kind is None: # only update title text
return doc._update_toc_item(xref, action=None, title=title)
if kind == pymupdf.LINK_GOTO:
if pno is None or pno not in range(1, doc.page_count + 1):
raise ValueError("bad page number")
page_xref = doc.page_xref(pno - 1)
page_height = doc.page_cropbox(pno - 1).height
if to is None:
to = pymupdf.Point(72, page_height - 36)
else:
to = pymupdf.Point(to)
to.y = page_height - to.y
ddict = {
"kind": kind,
"to": to,
"uri": uri,
"page": pno,
"file": filename,
"zoom": zoom,
}
action = getDestStr(page_xref, ddict)
if action == "" or not action.startswith("/A"):
raise ValueError("bad bookmark dest")
return doc._update_toc_item(xref, action=action[2:], title=title)
def get_area(*args) -> float:
"""Calculate area of rectangle.\nparameter is one of 'px' (default), 'in', 'cm', or 'mm'."""
rect = args[0]
if len(args) > 1:
unit = args[1]
else:
unit = "px"
u = {"px": (1, 1), "in": (1.0, 72.0), "cm": (2.54, 72.0), "mm": (25.4, 72.0)}
f = (u[unit][0] / u[unit][1]) ** 2
return f * rect.width * rect.height
def set_metadata(doc: pymupdf.Document, m: dict = None) -> None:
"""Update the PDF /Info object.
Args:
m: a dictionary like doc.metadata.
"""
if not doc.is_pdf:
raise ValueError("is no PDF")
if doc.is_closed or doc.is_encrypted:
raise ValueError("document closed or encrypted")
if m is None:
m = {}
elif type(m) is not dict:
raise ValueError("bad metadata")
keymap = {
"author": "Author",
"producer": "Producer",
"creator": "Creator",
"title": "Title",
"format": None,
"encryption": None,
"creationDate": "CreationDate",
"modDate": "ModDate",
"subject": "Subject",
"keywords": "Keywords",
"trapped": "Trapped",
}
valid_keys = set(keymap.keys())
diff_set = set(m.keys()).difference(valid_keys)
if diff_set != set():
msg = "bad dict key(s): %s" % diff_set
raise ValueError(msg)
t, temp = doc.xref_get_key(-1, "Info")
if t != "xref":
info_xref = 0
else:
info_xref = int(temp.replace("0 R", ""))
if m == {} and info_xref == 0: # nothing to do
return
if info_xref == 0: # no prev metadata: get new xref
info_xref = doc.get_new_xref()
doc.update_object(info_xref, "<<>>") # fill it with empty object
doc.xref_set_key(-1, "Info", "%i 0 R" % info_xref)
elif m == {}: # remove existing metadata
doc.xref_set_key(-1, "Info", "null")
doc.init_doc()
return
for key, val in [(k, v) for k, v in m.items() if keymap[k] is not None]:
pdf_key = keymap[key]
if not bool(val) or val in ("none", "null"):
val = "null"
else:
val = pymupdf.get_pdf_str(val)
doc.xref_set_key(info_xref, pdf_key, val)
doc.init_doc()
return
def getDestStr(xref: int, ddict: dict) -> str:
"""Calculate the PDF action string.
Notes:
Supports Link annotations and outline items (bookmarks).
"""
if not ddict:
return ""
str_goto = lambda a, b, c, d: f"/A<</S/GoTo/D[{a} 0 R/XYZ {_format_g((b, c, d))}]>>"
str_gotor1 = lambda a, b, c, d, e, f: f"/A<</S/GoToR/D[{a} /XYZ {_format_g((b, c, d))}]/F<</F{e}/UF{f}/Type/Filespec>>>>"
str_gotor2 = lambda a, b, c: f"/A<</S/GoToR/D{a}/F<</F{b}/UF{c}/Type/Filespec>>>>"
str_launch = lambda a, b: f"/A<</S/Launch/F<</F{a}/UF{b}/Type/Filespec>>>>"
str_uri = lambda a: f"/A<</S/URI/URI{a}>>"
if type(ddict) in (int, float):
dest = str_goto(xref, 0, ddict, 0)
return dest
d_kind = ddict.get("kind", pymupdf.LINK_NONE)
if d_kind == pymupdf.LINK_NONE:
return ""
if ddict["kind"] == pymupdf.LINK_GOTO:
d_zoom = ddict.get("zoom", 0)
to = ddict.get("to", pymupdf.Point(0, 0))
d_left, d_top = to
dest = str_goto(xref, d_left, d_top, d_zoom)
return dest
if ddict["kind"] == pymupdf.LINK_URI:
dest = str_uri(pymupdf.get_pdf_str(ddict["uri"]),)
return dest
if ddict["kind"] == pymupdf.LINK_LAUNCH:
fspec = pymupdf.get_pdf_str(ddict["file"])
dest = str_launch(fspec, fspec)
return dest
if ddict["kind"] == pymupdf.LINK_GOTOR and ddict["page"] < 0:
fspec = pymupdf.get_pdf_str(ddict["file"])
dest = str_gotor2(pymupdf.get_pdf_str(ddict["to"]), fspec, fspec)
return dest
if ddict["kind"] == pymupdf.LINK_GOTOR and ddict["page"] >= 0:
fspec = pymupdf.get_pdf_str(ddict["file"])
dest = str_gotor1(
ddict["page"],
ddict["to"].x,
ddict["to"].y,
ddict["zoom"],
fspec,
fspec,
)
return dest
return ""
def set_toc(
doc: pymupdf.Document,
toc: list,
collapse: int = 1,
) -> int:
"""Create new outline tree (table of contents, TOC).
Args:
toc: (list, tuple) each entry must contain level, title, page and
optionally top margin on the page. None or '()' remove the TOC.
collapse: (int) collapses entries beyond this level. Zero or None
shows all entries unfolded.
Returns:
the number of inserted items, or the number of removed items respectively.
"""
if doc.is_closed or doc.is_encrypted:
raise ValueError("document closed or encrypted")
if not doc.is_pdf:
raise ValueError("is no PDF")
if not toc: # remove all entries
return len(doc._delToC())
# validity checks --------------------------------------------------------
if type(toc) not in (list, tuple):
raise ValueError("'toc' must be list or tuple")
toclen = len(toc)
page_count = doc.page_count
t0 = toc[0]
if type(t0) not in (list, tuple):
raise ValueError("items must be sequences of 3 or 4 items")
if t0[0] != 1:
raise ValueError("hierarchy level of item 0 must be 1")
for i in list(range(toclen - 1)):
t1 = toc[i]
t2 = toc[i + 1]
if not -1 <= t1[2] <= page_count:
raise ValueError("row %i: page number out of range" % i)
if (type(t2) not in (list, tuple)) or len(t2) not in (3, 4):
raise ValueError("bad row %i" % (i + 1))
if (type(t2[0]) is not int) or t2[0] < 1:
raise ValueError("bad hierarchy level in row %i" % (i + 1))
if t2[0] > t1[0] + 1:
raise ValueError("bad hierarchy level in row %i" % (i + 1))
# no formal errors in toc --------------------------------------------------
# --------------------------------------------------------------------------
# make a list of xref numbers, which we can use for our TOC entries
# --------------------------------------------------------------------------
old_xrefs = doc._delToC() # del old outlines, get their xref numbers
# prepare table of xrefs for new bookmarks
old_xrefs = []
xref = [0] + old_xrefs
xref[0] = doc._getOLRootNumber() # entry zero is outline root xref number
if toclen > len(old_xrefs): # too few old xrefs?
for i in range((toclen - len(old_xrefs))):
xref.append(doc.get_new_xref()) # acquire new ones
lvltab = {0: 0} # to store last entry per hierarchy level
# ------------------------------------------------------------------------------
# contains new outline objects as strings - first one is the outline root
# ------------------------------------------------------------------------------
olitems = [{"count": 0, "first": -1, "last": -1, "xref": xref[0]}]
# ------------------------------------------------------------------------------
# build olitems as a list of PDF-like connected dictionaries
# ------------------------------------------------------------------------------
for i in range(toclen):
o = toc[i]
lvl = o[0] # level
title = pymupdf.get_pdf_str(o[1]) # title
pno = min(doc.page_count - 1, max(0, o[2] - 1)) # page number
page_xref = doc.page_xref(pno)
page_height = doc.page_cropbox(pno).height
top = pymupdf.Point(72, page_height - 36)
dest_dict = {"to": top, "kind": pymupdf.LINK_GOTO} # fall back target
if o[2] < 0:
dest_dict["kind"] = pymupdf.LINK_NONE
if len(o) > 3: # some target is specified
if type(o[3]) in (int, float): # convert a number to a point
dest_dict["to"] = pymupdf.Point(72, page_height - o[3])
else: # if something else, make sure we have a dict
# We make a copy of o[3] to avoid modifying our caller's data.
dest_dict = o[3].copy() if type(o[3]) is dict else dest_dict
if "to" not in dest_dict: # target point not in dict?
dest_dict["to"] = top # put default in
else: # transform target to PDF coordinates
page = doc[pno]
point = pymupdf.Point(dest_dict["to"])
point.y = page.cropbox.height - point.y
point = point * page.rotation_matrix
dest_dict["to"] = (point.x, point.y)
d = {}
d["first"] = -1
d["count"] = 0
d["last"] = -1
d["prev"] = -1
d["next"] = -1
d["dest"] = getDestStr(page_xref, dest_dict)
d["top"] = dest_dict["to"]
d["title"] = title
d["parent"] = lvltab[lvl - 1]
d["xref"] = xref[i + 1]
d["color"] = dest_dict.get("color")
d["flags"] = dest_dict.get("italic", 0) + 2 * dest_dict.get("bold", 0)
lvltab[lvl] = i + 1
parent = olitems[lvltab[lvl - 1]] # the parent entry
if (
dest_dict.get("collapse") or collapse and lvl > collapse
): # suppress expansion
parent["count"] -= 1 # make /Count negative
else:
parent["count"] += 1 # positive /Count
if parent["first"] == -1:
parent["first"] = i + 1
parent["last"] = i + 1
else:
d["prev"] = parent["last"]
prev = olitems[parent["last"]]
prev["next"] = i + 1
parent["last"] = i + 1
olitems.append(d)
# ------------------------------------------------------------------------------
# now create each outline item as a string and insert it in the PDF
# ------------------------------------------------------------------------------
for i, ol in enumerate(olitems):
txt = "<<"
if ol["count"] != 0:
txt += "/Count %i" % ol["count"]
try:
txt += ol["dest"]
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose >= 2: pymupdf.exception_info()
pass
try:
if ol["first"] > -1:
txt += "/First %i 0 R" % xref[ol["first"]]
except Exception:
if g_exceptions_verbose >= 2: pymupdf.exception_info()
pass
try:
if ol["last"] > -1:
txt += "/Last %i 0 R" % xref[ol["last"]]
except Exception:
if g_exceptions_verbose >= 2: pymupdf.exception_info()
pass
try:
if ol["next"] > -1:
txt += "/Next %i 0 R" % xref[ol["next"]]
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose >= 2: pymupdf.exception_info()
pass
try:
if ol["parent"] > -1:
txt += "/Parent %i 0 R" % xref[ol["parent"]]
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose >= 2: pymupdf.exception_info()
pass
try:
if ol["prev"] > -1:
txt += "/Prev %i 0 R" % xref[ol["prev"]]
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose >= 2: pymupdf.exception_info()
pass
try:
txt += "/Title" + ol["title"]
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose >= 2: pymupdf.exception_info()
pass
if ol.get("color") and len(ol["color"]) == 3:
txt += f"/C[ {_format_g(tuple(ol['color']))}]"
if ol.get("flags", 0) > 0:
txt += "/F %i" % ol["flags"]
if i == 0: # special: this is the outline root
txt += "/Type/Outlines" # so add the /Type entry
txt += ">>"
doc.update_object(xref[i], txt) # insert the PDF object
doc.init_doc()
return toclen
def do_links(
doc1: pymupdf.Document,
doc2: pymupdf.Document,
from_page: int = -1,
to_page: int = -1,
start_at: int = -1,
) -> None:
"""Insert links contained in copied page range into destination PDF.
Parameter values **must** equal those of method insert_pdf(), which must
have been previously executed.
"""
#pymupdf.log( 'utils.do_links()')
# --------------------------------------------------------------------------
# internal function to create the actual "/Annots" object string
# --------------------------------------------------------------------------
def cre_annot(lnk, xref_dst, pno_src, ctm):
"""Create annotation object string for a passed-in link."""
r = lnk["from"] * ctm # rect in PDF coordinates
rect = _format_g(tuple(r))
if lnk["kind"] == pymupdf.LINK_GOTO:
txt = pymupdf.annot_skel["goto1"] # annot_goto
idx = pno_src.index(lnk["page"])
p = lnk["to"] * ctm # target point in PDF coordinates
annot = txt(xref_dst[idx], p.x, p.y, lnk["zoom"], rect)
elif lnk["kind"] == pymupdf.LINK_GOTOR:
if lnk["page"] >= 0:
txt = pymupdf.annot_skel["gotor1"] # annot_gotor
pnt = lnk.get("to", pymupdf.Point(0, 0)) # destination point
if type(pnt) is not pymupdf.Point:
pnt = pymupdf.Point(0, 0)
annot = txt(
lnk["page"],
pnt.x,
pnt.y,
lnk["zoom"],
lnk["file"],
lnk["file"],
rect,
)
else:
txt = pymupdf.annot_skel["gotor2"] # annot_gotor_n
to = pymupdf.get_pdf_str(lnk["to"])
to = to[1:-1]
f = lnk["file"]
annot = txt(to, f, rect)
elif lnk["kind"] == pymupdf.LINK_LAUNCH:
txt = pymupdf.annot_skel["launch"] # annot_launch
annot = txt(lnk["file"], lnk["file"], rect)
elif lnk["kind"] == pymupdf.LINK_URI:
txt = pymupdf.annot_skel["uri"] # annot_uri
annot = txt(lnk["uri"], rect)
else:
annot = ""
return annot
# --------------------------------------------------------------------------
# validate & normalize parameters
if from_page < 0:
fp = 0
elif from_page >= doc2.page_count:
fp = doc2.page_count - 1
else:
fp = from_page
if to_page < 0 or to_page >= doc2.page_count:
tp = doc2.page_count - 1
else:
tp = to_page
if start_at < 0:
raise ValueError("'start_at' must be >= 0")
sa = start_at
incr = 1 if fp <= tp else -1 # page range could be reversed
# lists of source / destination page numbers
pno_src = list(range(fp, tp + incr, incr))
pno_dst = [sa + i for i in range(len(pno_src))]
# lists of source / destination page xrefs
xref_src = []
xref_dst = []
for i in range(len(pno_src)):
p_src = pno_src[i]
p_dst = pno_dst[i]
old_xref = doc2.page_xref(p_src)
new_xref = doc1.page_xref(p_dst)
xref_src.append(old_xref)
xref_dst.append(new_xref)
# create the links for each copied page in destination PDF
for i in range(len(xref_src)):
page_src = doc2[pno_src[i]] # load source page
links = page_src.get_links() # get all its links
#pymupdf.log( '{pno_src=}')
#pymupdf.log( '{type(page_src)=}')
#pymupdf.log( '{page_src=}')
#pymupdf.log( '{=i len(links)}')
if len(links) == 0: # no links there
page_src = None
continue
ctm = ~page_src.transformation_matrix # calc page transformation matrix
page_dst = doc1[pno_dst[i]] # load destination page
link_tab = [] # store all link definitions here
for l in links:
if l["kind"] == pymupdf.LINK_GOTO and (l["page"] not in pno_src):
continue # GOTO link target not in copied pages
annot_text = cre_annot(l, xref_dst, pno_src, ctm)
if annot_text:
link_tab.append(annot_text)
if link_tab != []:
page_dst._addAnnot_FromString( tuple(link_tab))
#pymupdf.log( 'utils.do_links() returning.')
def getLinkText(page: pymupdf.Page, lnk: dict) -> str:
# --------------------------------------------------------------------------
# define skeletons for /Annots object texts
# --------------------------------------------------------------------------
ctm = page.transformation_matrix
ictm = ~ctm
r = lnk["from"]
rect = _format_g(tuple(r * ictm))
annot = ""
if lnk["kind"] == pymupdf.LINK_GOTO:
if lnk["page"] >= 0:
txt = pymupdf.annot_skel["goto1"] # annot_goto
pno = lnk["page"]
xref = page.parent.page_xref(pno)
pnt = lnk.get("to", pymupdf.Point(0, 0)) # destination point
dest_page = page.parent[pno]
dest_ctm = dest_page.transformation_matrix
dest_ictm = ~dest_ctm
ipnt = pnt * dest_ictm
annot = txt(xref, ipnt.x, ipnt.y, lnk.get("zoom", 0), rect)
else:
txt = pymupdf.annot_skel["goto2"] # annot_goto_n
annot = txt(pymupdf.get_pdf_str(lnk["to"]), rect)
elif lnk["kind"] == pymupdf.LINK_GOTOR:
if lnk["page"] >= 0:
txt = pymupdf.annot_skel["gotor1"] # annot_gotor
pnt = lnk.get("to", pymupdf.Point(0, 0)) # destination point
if type(pnt) is not pymupdf.Point:
pnt = pymupdf.Point(0, 0)
annot = txt(
lnk["page"],
pnt.x,
pnt.y,
lnk.get("zoom", 0),
lnk["file"],
lnk["file"],
rect,
)
else:
txt = pymupdf.annot_skel["gotor2"] # annot_gotor_n
annot = txt(pymupdf.get_pdf_str(lnk["to"]), lnk["file"], rect)
elif lnk["kind"] == pymupdf.LINK_LAUNCH:
txt = pymupdf.annot_skel["launch"] # annot_launch
annot = txt(lnk["file"], lnk["file"], rect)
elif lnk["kind"] == pymupdf.LINK_URI:
txt = pymupdf.annot_skel["uri"] # txt = annot_uri
annot = txt(lnk["uri"], rect)
elif lnk["kind"] == pymupdf.LINK_NAMED:
txt = pymupdf.annot_skel["named"] # annot_named
lname = lnk.get("name") # check presence of key
if lname is None: # if missing, fall back to alternative
lname = lnk["nameddest"]
annot = txt(lname, rect)
if not annot:
return annot
# add a /NM PDF key to the object definition
link_names = dict( # existing ids and their xref
[(x[0], x[2]) for x in page.annot_xrefs() if x[1] == pymupdf.PDF_ANNOT_LINK] # pylint: disable=no-member
)
old_name = lnk.get("id", "") # id value in the argument
if old_name and (lnk["xref"], old_name) in link_names.items():
name = old_name # no new name if this is an update only
else:
i = 0
stem = pymupdf.TOOLS.set_annot_stem() + "-L%i"
while True:
name = stem % i
if name not in link_names.values():
break
i += 1
# add /NM key to object definition
annot = annot.replace("/Link", "/Link/NM(%s)" % name)
return annot
def delete_widget(page: pymupdf.Page, widget: pymupdf.Widget) -> pymupdf.Widget:
"""Delete widget from page and return the next one."""
pymupdf.CheckParent(page)
annot = getattr(widget, "_annot", None)
if annot is None:
raise ValueError("bad type: widget")
nextwidget = widget.next
page.delete_annot(annot)
widget._annot.parent = None
keylist = list(widget.__dict__.keys())
for key in keylist:
del widget.__dict__[key]
return nextwidget
def update_link(page: pymupdf.Page, lnk: dict) -> None:
"""Update a link on the current page."""
pymupdf.CheckParent(page)
annot = getLinkText(page, lnk)
if annot == "":
raise ValueError("link kind not supported")
page.parent.update_object(lnk["xref"], annot, page=page)
def insert_link(page: pymupdf.Page, lnk: dict, mark: bool = True) -> None:
"""Insert a new link for the current page."""
pymupdf.CheckParent(page)
annot = getLinkText(page, lnk)
if annot == "":
raise ValueError("link kind not supported")
page._addAnnot_FromString((annot,))
def insert_textbox(
page: pymupdf.Page,
rect: rect_like,
buffer: typing.Union[str, list],
fontname: str = "helv",
fontfile: OptStr = None,
set_simple: int = 0,
encoding: int = 0,
fontsize: float = 11,
lineheight: OptFloat = None,
color: OptSeq = None,
fill: OptSeq = None,
expandtabs: int = 1,
align: int = 0,
rotate: int = 0,
render_mode: int = 0,
border_width: float = 0.05,
morph: OptSeq = None,
overlay: bool = True,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> float:
"""Insert text into a given rectangle.
Notes:
Creates a Shape object, uses its same-named method and commits it.
Parameters:
rect: (rect-like) area to use for text.
buffer: text to be inserted
fontname: a Base-14 font, font name or '/name'
fontfile: name of a font file
fontsize: font size
lineheight: overwrite the font property
color: RGB color triple
expandtabs: handles tabulators with string function
align: left, center, right, justified
rotate: 0, 90, 180, or 270 degrees
morph: morph box with a matrix and a fixpoint
overlay: put text in foreground or background
Returns:
unused or deficit rectangle area (float)
"""
img = page.new_shape()
rc = img.insert_textbox(
rect,
buffer,
fontsize=fontsize,
lineheight=lineheight,
fontname=fontname,
fontfile=fontfile,
set_simple=set_simple,
encoding=encoding,
color=color,
fill=fill,
expandtabs=expandtabs,
render_mode=render_mode,
border_width=border_width,
align=align,
rotate=rotate,
morph=morph,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
if rc >= 0:
img.commit(overlay)
return rc
def insert_text(
page: pymupdf.Page,
point: point_like,
text: typing.Union[str, list],
fontsize: float = 11,
lineheight: OptFloat = None,
fontname: str = "helv",
fontfile: OptStr = None,
set_simple: int = 0,
encoding: int = 0,
color: OptSeq = None,
fill: OptSeq = None,
border_width: float = 0.05,
render_mode: int = 0,
rotate: int = 0,
morph: OptSeq = None,
overlay: bool = True,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
):
img = page.new_shape()
rc = img.insert_text(
point,
text,
fontsize=fontsize,
lineheight=lineheight,
fontname=fontname,
fontfile=fontfile,
set_simple=set_simple,
encoding=encoding,
color=color,
fill=fill,
border_width=border_width,
render_mode=render_mode,
rotate=rotate,
morph=morph,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
if rc >= 0:
img.commit(overlay)
return rc
def insert_htmlbox(
page,
rect,
text,
*,
css=None,
scale_low=0,
archive=None,
rotate=0,
oc=0,
opacity=1,
overlay=True,
) -> float:
"""Insert text with optional HTML tags and stylings into a rectangle.
Args:
rect: (rect-like) rectangle into which the text should be placed.
text: (str) text with optional HTML tags and stylings.
css: (str) CSS styling commands.
scale_low: (float) force-fit content by scaling it down. Must be in
range [0, 1]. If 1, no scaling will take place. If 0, arbitrary
down-scaling is acceptable. A value of 0.1 would mean that content
may be scaled down by at most 90%.
archive: Archive object pointing to locations of used fonts or images
rotate: (int) rotate the text in the box by a multiple of 90 degrees.
oc: (int) the xref of an OCG / OCMD (Optional Content).
opacity: (float) set opacity of inserted content.
overlay: (bool) put text on top of page content.
Returns:
A tuple of floats (spare_height, scale).
spare_height: -1 if content did not fit, else >= 0. It is the height of the
unused (still available) rectangle stripe. Positive only if
scale_min = 1 (no down scaling).
scale: downscaling factor, 0 < scale <= 1. Set to 0 if spare_height = -1 (no fit).
"""
# normalize rotation angle
if not rotate % 90 == 0:
raise ValueError("bad rotation angle")
while rotate < 0:
rotate += 360
while rotate >= 360:
rotate -= 360
if not 0 <= scale_low <= 1:
raise ValueError("'scale_low' must be in [0, 1]")
if css is None:
css = ""
rect = pymupdf.Rect(rect)
if rotate in (90, 270):
temp_rect = pymupdf.Rect(0, 0, rect.height, rect.width)
else:
temp_rect = pymupdf.Rect(0, 0, rect.width, rect.height)
# use a small border by default
mycss = "body {margin:1px;}" + css # append user CSS
# either make a story, or accept a given one
if isinstance(text, str): # if a string, convert to a Story
story = pymupdf.Story(html=text, user_css=mycss, archive=archive)
elif isinstance(text, pymupdf.Story):
story = text
else:
raise ValueError("'text' must be a string or a Story")
# ----------------------------------------------------------------
# Find a scaling factor that lets our story fit in
# ----------------------------------------------------------------
scale_max = None if scale_low == 0 else 1 / scale_low
fit = story.fit_scale(temp_rect, scale_min=1, scale_max=scale_max)
if not fit.big_enough: # there was no fit
return (-1, scale_low)
filled = fit.filled
scale = 1 / fit.parameter # shrink factor
spare_height = fit.rect.y1 - filled[3] # unused room at rectangle bottom
# Note: due to MuPDF's logic this may be negative even for successful fits.
if scale != 1 or spare_height < 0: # if scaling occurred, set spare_height to 0
spare_height = 0
def rect_function(*args):
return fit.rect, fit.rect, pymupdf.Identity
# draw story on temp PDF page
doc = story.write_with_links(rect_function)
# Insert opacity if requested.
# For this, we prepend a command to the /Contents.
if 0 <= opacity < 1:
tpage = doc[0] # load page
# generate /ExtGstate for the page
alp0 = tpage._set_opacity(CA=opacity, ca=opacity)
s = f"/{alp0} gs\n" # generate graphic state command
pymupdf.TOOLS._insert_contents(tpage, s.encode(), 0)
# put result in target page
page.show_pdf_page(rect, doc, 0, rotate=rotate, oc=oc, overlay=overlay)
# -------------------------------------------------------------------------
# re-insert links in target rect (show_pdf_page cannot copy annotations)
# -------------------------------------------------------------------------
# scaled center point of fit.rect
mp1 = (fit.rect.tl + fit.rect.br) / 2 * scale
# center point of target rect
mp2 = (rect.tl + rect.br) / 2
# compute link positioning matrix:
# - move center of scaled-down fit.rect to (0,0)
# - rotate
# - move (0,0) to center of target rect
mat = (
pymupdf.Matrix(scale, 0, 0, scale, -mp1.x, -mp1.y)
* pymupdf.Matrix(-rotate)
* pymupdf.Matrix(1, 0, 0, 1, mp2.x, mp2.y)
)
# copy over links
for link in doc[0].get_links():
link["from"] *= mat
page.insert_link(link)
return spare_height, scale
def new_page(
doc: pymupdf.Document,
pno: int = -1,
width: float = 595,
height: float = 842,
) -> pymupdf.Page:
"""Create and return a new page object.
Args:
pno: (int) insert before this page. Default: after last page.
width: (float) page width in points. Default: 595 (ISO A4 width).
height: (float) page height in points. Default 842 (ISO A4 height).
Returns:
A pymupdf.Page object.
"""
doc._newPage(pno, width=width, height=height)
return doc[pno]
def insert_page(
doc: pymupdf.Document,
pno: int,
text: typing.Union[str, list, None] = None,
fontsize: float = 11,
width: float = 595,
height: float = 842,
fontname: str = "helv",
fontfile: OptStr = None,
color: OptSeq = (0,),
) -> int:
"""Create a new PDF page and insert some text.
Notes:
Function combining pymupdf.Document.new_page() and pymupdf.Page.insert_text().
For parameter details see these methods.
"""
page = doc.new_page(pno=pno, width=width, height=height)
if not bool(text):
return 0
rc = page.insert_text(
(50, 72),
text,
fontsize=fontsize,
fontname=fontname,
fontfile=fontfile,
color=color,
)
return rc
def draw_line(
page: pymupdf.Page,
p1: point_like,
p2: point_like,
color: OptSeq = (0,),
dashes: OptStr = None,
width: float = 1,
lineCap: int = 0,
lineJoin: int = 0,
overlay: bool = True,
morph: OptSeq = None,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc=0,
) -> pymupdf.Point:
"""Draw a line from point p1 to point p2."""
img = page.new_shape()
p = img.draw_line(pymupdf.Point(p1), pymupdf.Point(p2))
img.finish(
color=color,
dashes=dashes,
width=width,
closePath=False,
lineCap=lineCap,
lineJoin=lineJoin,
morph=morph,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
img.commit(overlay)
return p
def draw_squiggle(
page: pymupdf.Page,
p1: point_like,
p2: point_like,
breadth: float = 2,
color: OptSeq = (0,),
dashes: OptStr = None,
width: float = 1,
lineCap: int = 0,
lineJoin: int = 0,
overlay: bool = True,
morph: OptSeq = None,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> pymupdf.Point:
"""Draw a squiggly line from point p1 to point p2."""
img = page.new_shape()
p = img.draw_squiggle(pymupdf.Point(p1), pymupdf.Point(p2), breadth=breadth)
img.finish(
color=color,
dashes=dashes,
width=width,
closePath=False,
lineCap=lineCap,
lineJoin=lineJoin,
morph=morph,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
img.commit(overlay)
return p
def draw_zigzag(
page: pymupdf.Page,
p1: point_like,
p2: point_like,
breadth: float = 2,
color: OptSeq = (0,),
dashes: OptStr = None,
width: float = 1,
lineCap: int = 0,
lineJoin: int = 0,
overlay: bool = True,
morph: OptSeq = None,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> pymupdf.Point:
"""Draw a zigzag line from point p1 to point p2."""
img = page.new_shape()
p = img.draw_zigzag(pymupdf.Point(p1), pymupdf.Point(p2), breadth=breadth)
img.finish(
color=color,
dashes=dashes,
width=width,
closePath=False,
lineCap=lineCap,
lineJoin=lineJoin,
morph=morph,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
img.commit(overlay)
return p
def draw_rect(
page: pymupdf.Page,
rect: rect_like,
color: OptSeq = (0,),
fill: OptSeq = None,
dashes: OptStr = None,
width: float = 1,
lineCap: int = 0,
lineJoin: int = 0,
morph: OptSeq = None,
overlay: bool = True,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
radius=None,
) -> pymupdf.Point:
'''
Draw a rectangle. See Shape class method for details.
'''
img = page.new_shape()
Q = img.draw_rect(pymupdf.Rect(rect), radius=radius)
img.finish(
color=color,
fill=fill,
dashes=dashes,
width=width,
lineCap=lineCap,
lineJoin=lineJoin,
morph=morph,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
img.commit(overlay)
return Q
def draw_quad(
page: pymupdf.Page,
quad: quad_like,
color: OptSeq = (0,),
fill: OptSeq = None,
dashes: OptStr = None,
width: float = 1,
lineCap: int = 0,
lineJoin: int = 0,
morph: OptSeq = None,
overlay: bool = True,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> pymupdf.Point:
"""Draw a quadrilateral."""
img = page.new_shape()
Q = img.draw_quad(pymupdf.Quad(quad))
img.finish(
color=color,
fill=fill,
dashes=dashes,
width=width,
lineCap=lineCap,
lineJoin=lineJoin,
morph=morph,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
img.commit(overlay)
return Q
def draw_polyline(
page: pymupdf.Page,
points: list,
color: OptSeq = (0,),
fill: OptSeq = None,
dashes: OptStr = None,
width: float = 1,
morph: OptSeq = None,
lineCap: int = 0,
lineJoin: int = 0,
overlay: bool = True,
closePath: bool = False,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> pymupdf.Point:
"""Draw multiple connected line segments."""
img = page.new_shape()
Q = img.draw_polyline(points)
img.finish(
color=color,
fill=fill,
dashes=dashes,
width=width,
lineCap=lineCap,
lineJoin=lineJoin,
morph=morph,
closePath=closePath,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
img.commit(overlay)
return Q
def draw_circle(
page: pymupdf.Page,
center: point_like,
radius: float,
color: OptSeq = (0,),
fill: OptSeq = None,
morph: OptSeq = None,
dashes: OptStr = None,
width: float = 1,
lineCap: int = 0,
lineJoin: int = 0,
overlay: bool = True,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> pymupdf.Point:
"""Draw a circle given its center and radius."""
img = page.new_shape()
Q = img.draw_circle(pymupdf.Point(center), radius)
img.finish(
color=color,
fill=fill,
dashes=dashes,
width=width,
lineCap=lineCap,
lineJoin=lineJoin,
morph=morph,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
img.commit(overlay)
return Q
def draw_oval(
page: pymupdf.Page,
rect: typing.Union[rect_like, quad_like],
color: OptSeq = (0,),
fill: OptSeq = None,
dashes: OptStr = None,
morph: OptSeq = None,
width: float = 1,
lineCap: int = 0,
lineJoin: int = 0,
overlay: bool = True,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> pymupdf.Point:
"""Draw an oval given its containing rectangle or quad."""
img = page.new_shape()
Q = img.draw_oval(rect)
img.finish(
color=color,
fill=fill,
dashes=dashes,
width=width,
lineCap=lineCap,
lineJoin=lineJoin,
morph=morph,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
img.commit(overlay)
return Q
def draw_curve(
page: pymupdf.Page,
p1: point_like,
p2: point_like,
p3: point_like,
color: OptSeq = (0,),
fill: OptSeq = None,
dashes: OptStr = None,
width: float = 1,
morph: OptSeq = None,
closePath: bool = False,
lineCap: int = 0,
lineJoin: int = 0,
overlay: bool = True,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> pymupdf.Point:
"""Draw a special Bezier curve from p1 to p3, generating control points on lines p1 to p2 and p2 to p3."""
img = page.new_shape()
Q = img.draw_curve(pymupdf.Point(p1), pymupdf.Point(p2), pymupdf.Point(p3))
img.finish(
color=color,
fill=fill,
dashes=dashes,
width=width,
lineCap=lineCap,
lineJoin=lineJoin,
morph=morph,
closePath=closePath,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
img.commit(overlay)
return Q
def draw_bezier(
page: pymupdf.Page,
p1: point_like,
p2: point_like,
p3: point_like,
p4: point_like,
color: OptSeq = (0,),
fill: OptSeq = None,
dashes: OptStr = None,
width: float = 1,
morph: OptStr = None,
closePath: bool = False,
lineCap: int = 0,
lineJoin: int = 0,
overlay: bool = True,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> pymupdf.Point:
"""Draw a general cubic Bezier curve from p1 to p4 using control points p2 and p3."""
img = page.new_shape()
Q = img.draw_bezier(pymupdf.Point(p1), pymupdf.Point(p2), pymupdf.Point(p3), pymupdf.Point(p4))
img.finish(
color=color,
fill=fill,
dashes=dashes,
width=width,
lineCap=lineCap,
lineJoin=lineJoin,
morph=morph,
closePath=closePath,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
img.commit(overlay)
return Q
def draw_sector(
page: pymupdf.Page,
center: point_like,
point: point_like,
beta: float,
color: OptSeq = (0,),
fill: OptSeq = None,
dashes: OptStr = None,
fullSector: bool = True,
morph: OptSeq = None,
width: float = 1,
closePath: bool = False,
lineCap: int = 0,
lineJoin: int = 0,
overlay: bool = True,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> pymupdf.Point:
"""Draw a circle sector given circle center, one arc end point and the angle of the arc.
Parameters:
center -- center of circle
point -- arc end point
beta -- angle of arc (degrees)
fullSector -- connect arc ends with center
"""
img = page.new_shape()
Q = img.draw_sector(pymupdf.Point(center), pymupdf.Point(point), beta, fullSector=fullSector)
img.finish(
color=color,
fill=fill,
dashes=dashes,
width=width,
lineCap=lineCap,
lineJoin=lineJoin,
morph=morph,
closePath=closePath,
stroke_opacity=stroke_opacity,
fill_opacity=fill_opacity,
oc=oc,
)
img.commit(overlay)
return Q
# ----------------------------------------------------------------------
# Name: wx.lib.colourdb.py
# Purpose: Adds a bunch of colour names and RGB values to the
# colour database so they can be found by name
#
# Author: Robin Dunn
#
# Created: 13-March-2001
# Copyright: (c) 2001-2017 by Total Control Software
# Licence: wxWindows license
# Tags: phoenix-port, unittest, documented
# ----------------------------------------------------------------------
def getColorList() -> list:
"""
Returns a list of just the colour names used by this module.
:rtype: list of strings
"""
return [x[0] for x in getColorInfoList()]
def getColorInfoList() -> list:
"""
Returns the list of colour name/value tuples used by this module.
:rtype: list of tuples
"""
return [
("ALICEBLUE", 240, 248, 255),
("ANTIQUEWHITE", 250, 235, 215),
("ANTIQUEWHITE1", 255, 239, 219),
("ANTIQUEWHITE2", 238, 223, 204),
("ANTIQUEWHITE3", 205, 192, 176),
("ANTIQUEWHITE4", 139, 131, 120),
("AQUAMARINE", 127, 255, 212),
("AQUAMARINE1", 127, 255, 212),
("AQUAMARINE2", 118, 238, 198),
("AQUAMARINE3", 102, 205, 170),
("AQUAMARINE4", 69, 139, 116),
("AZURE", 240, 255, 255),
("AZURE1", 240, 255, 255),
("AZURE2", 224, 238, 238),
("AZURE3", 193, 205, 205),
("AZURE4", 131, 139, 139),
("BEIGE", 245, 245, 220),
("BISQUE", 255, 228, 196),
("BISQUE1", 255, 228, 196),
("BISQUE2", 238, 213, 183),
("BISQUE3", 205, 183, 158),
("BISQUE4", 139, 125, 107),
("BLACK", 0, 0, 0),
("BLANCHEDALMOND", 255, 235, 205),
("BLUE", 0, 0, 255),
("BLUE1", 0, 0, 255),
("BLUE2", 0, 0, 238),
("BLUE3", 0, 0, 205),
("BLUE4", 0, 0, 139),
("BLUEVIOLET", 138, 43, 226),
("BROWN", 165, 42, 42),
("BROWN1", 255, 64, 64),
("BROWN2", 238, 59, 59),
("BROWN3", 205, 51, 51),
("BROWN4", 139, 35, 35),
("BURLYWOOD", 222, 184, 135),
("BURLYWOOD1", 255, 211, 155),
("BURLYWOOD2", 238, 197, 145),
("BURLYWOOD3", 205, 170, 125),
("BURLYWOOD4", 139, 115, 85),
("CADETBLUE", 95, 158, 160),
("CADETBLUE1", 152, 245, 255),
("CADETBLUE2", 142, 229, 238),
("CADETBLUE3", 122, 197, 205),
("CADETBLUE4", 83, 134, 139),
("CHARTREUSE", 127, 255, 0),
("CHARTREUSE1", 127, 255, 0),
("CHARTREUSE2", 118, 238, 0),
("CHARTREUSE3", 102, 205, 0),
("CHARTREUSE4", 69, 139, 0),
("CHOCOLATE", 210, 105, 30),
("CHOCOLATE1", 255, 127, 36),
("CHOCOLATE2", 238, 118, 33),
("CHOCOLATE3", 205, 102, 29),
("CHOCOLATE4", 139, 69, 19),
("COFFEE", 156, 79, 0),
("CORAL", 255, 127, 80),
("CORAL1", 255, 114, 86),
("CORAL2", 238, 106, 80),
("CORAL3", 205, 91, 69),
("CORAL4", 139, 62, 47),
("CORNFLOWERBLUE", 100, 149, 237),
("CORNSILK", 255, 248, 220),
("CORNSILK1", 255, 248, 220),
("CORNSILK2", 238, 232, 205),
("CORNSILK3", 205, 200, 177),
("CORNSILK4", 139, 136, 120),
("CYAN", 0, 255, 255),
("CYAN1", 0, 255, 255),
("CYAN2", 0, 238, 238),
("CYAN3", 0, 205, 205),
("CYAN4", 0, 139, 139),
("DARKBLUE", 0, 0, 139),
("DARKCYAN", 0, 139, 139),
("DARKGOLDENROD", 184, 134, 11),
("DARKGOLDENROD1", 255, 185, 15),
("DARKGOLDENROD2", 238, 173, 14),
("DARKGOLDENROD3", 205, 149, 12),
("DARKGOLDENROD4", 139, 101, 8),
("DARKGREEN", 0, 100, 0),
("DARKGRAY", 169, 169, 169),
("DARKKHAKI", 189, 183, 107),
("DARKMAGENTA", 139, 0, 139),
("DARKOLIVEGREEN", 85, 107, 47),
("DARKOLIVEGREEN1", 202, 255, 112),
("DARKOLIVEGREEN2", 188, 238, 104),
("DARKOLIVEGREEN3", 162, 205, 90),
("DARKOLIVEGREEN4", 110, 139, 61),
("DARKORANGE", 255, 140, 0),
("DARKORANGE1", 255, 127, 0),
("DARKORANGE2", 238, 118, 0),
("DARKORANGE3", 205, 102, 0),
("DARKORANGE4", 139, 69, 0),
("DARKORCHID", 153, 50, 204),
("DARKORCHID1", 191, 62, 255),
("DARKORCHID2", 178, 58, 238),
("DARKORCHID3", 154, 50, 205),
("DARKORCHID4", 104, 34, 139),
("DARKRED", 139, 0, 0),
("DARKSALMON", 233, 150, 122),
("DARKSEAGREEN", 143, 188, 143),
("DARKSEAGREEN1", 193, 255, 193),
("DARKSEAGREEN2", 180, 238, 180),
("DARKSEAGREEN3", 155, 205, 155),
("DARKSEAGREEN4", 105, 139, 105),
("DARKSLATEBLUE", 72, 61, 139),
("DARKSLATEGRAY", 47, 79, 79),
("DARKTURQUOISE", 0, 206, 209),
("DARKVIOLET", 148, 0, 211),
("DEEPPINK", 255, 20, 147),
("DEEPPINK1", 255, 20, 147),
("DEEPPINK2", 238, 18, 137),
("DEEPPINK3", 205, 16, 118),
("DEEPPINK4", 139, 10, 80),
("DEEPSKYBLUE", 0, 191, 255),
("DEEPSKYBLUE1", 0, 191, 255),
("DEEPSKYBLUE2", 0, 178, 238),
("DEEPSKYBLUE3", 0, 154, 205),
("DEEPSKYBLUE4", 0, 104, 139),
("DIMGRAY", 105, 105, 105),
("DODGERBLUE", 30, 144, 255),
("DODGERBLUE1", 30, 144, 255),
("DODGERBLUE2", 28, 134, 238),
("DODGERBLUE3", 24, 116, 205),
("DODGERBLUE4", 16, 78, 139),
("FIREBRICK", 178, 34, 34),
("FIREBRICK1", 255, 48, 48),
("FIREBRICK2", 238, 44, 44),
("FIREBRICK3", 205, 38, 38),
("FIREBRICK4", 139, 26, 26),
("FLORALWHITE", 255, 250, 240),
("FORESTGREEN", 34, 139, 34),
("GAINSBORO", 220, 220, 220),
("GHOSTWHITE", 248, 248, 255),
("GOLD", 255, 215, 0),
("GOLD1", 255, 215, 0),
("GOLD2", 238, 201, 0),
("GOLD3", 205, 173, 0),
("GOLD4", 139, 117, 0),
("GOLDENROD", 218, 165, 32),
("GOLDENROD1", 255, 193, 37),
("GOLDENROD2", 238, 180, 34),
("GOLDENROD3", 205, 155, 29),
("GOLDENROD4", 139, 105, 20),
("GREEN YELLOW", 173, 255, 47),
("GREEN", 0, 255, 0),
("GREEN1", 0, 255, 0),
("GREEN2", 0, 238, 0),
("GREEN3", 0, 205, 0),
("GREEN4", 0, 139, 0),
("GREENYELLOW", 173, 255, 47),
("GRAY", 190, 190, 190),
("GRAY0", 0, 0, 0),
("GRAY1", 3, 3, 3),
("GRAY10", 26, 26, 26),
("GRAY100", 255, 255, 255),
("GRAY11", 28, 28, 28),
("GRAY12", 31, 31, 31),
("GRAY13", 33, 33, 33),
("GRAY14", 36, 36, 36),
("GRAY15", 38, 38, 38),
("GRAY16", 41, 41, 41),
("GRAY17", 43, 43, 43),
("GRAY18", 46, 46, 46),
("GRAY19", 48, 48, 48),
("GRAY2", 5, 5, 5),
("GRAY20", 51, 51, 51),
("GRAY21", 54, 54, 54),
("GRAY22", 56, 56, 56),
("GRAY23", 59, 59, 59),
("GRAY24", 61, 61, 61),
("GRAY25", 64, 64, 64),
("GRAY26", 66, 66, 66),
("GRAY27", 69, 69, 69),
("GRAY28", 71, 71, 71),
("GRAY29", 74, 74, 74),
("GRAY3", 8, 8, 8),
("GRAY30", 77, 77, 77),
("GRAY31", 79, 79, 79),
("GRAY32", 82, 82, 82),
("GRAY33", 84, 84, 84),
("GRAY34", 87, 87, 87),
("GRAY35", 89, 89, 89),
("GRAY36", 92, 92, 92),
("GRAY37", 94, 94, 94),
("GRAY38", 97, 97, 97),
("GRAY39", 99, 99, 99),
("GRAY4", 10, 10, 10),
("GRAY40", 102, 102, 102),
("GRAY41", 105, 105, 105),
("GRAY42", 107, 107, 107),
("GRAY43", 110, 110, 110),
("GRAY44", 112, 112, 112),
("GRAY45", 115, 115, 115),
("GRAY46", 117, 117, 117),
("GRAY47", 120, 120, 120),
("GRAY48", 122, 122, 122),
("GRAY49", 125, 125, 125),
("GRAY5", 13, 13, 13),
("GRAY50", 127, 127, 127),
("GRAY51", 130, 130, 130),
("GRAY52", 133, 133, 133),
("GRAY53", 135, 135, 135),
("GRAY54", 138, 138, 138),
("GRAY55", 140, 140, 140),
("GRAY56", 143, 143, 143),
("GRAY57", 145, 145, 145),
("GRAY58", 148, 148, 148),
("GRAY59", 150, 150, 150),
("GRAY6", 15, 15, 15),
("GRAY60", 153, 153, 153),
("GRAY61", 156, 156, 156),
("GRAY62", 158, 158, 158),
("GRAY63", 161, 161, 161),
("GRAY64", 163, 163, 163),
("GRAY65", 166, 166, 166),
("GRAY66", 168, 168, 168),
("GRAY67", 171, 171, 171),
("GRAY68", 173, 173, 173),
("GRAY69", 176, 176, 176),
("GRAY7", 18, 18, 18),
("GRAY70", 179, 179, 179),
("GRAY71", 181, 181, 181),
("GRAY72", 184, 184, 184),
("GRAY73", 186, 186, 186),
("GRAY74", 189, 189, 189),
("GRAY75", 191, 191, 191),
("GRAY76", 194, 194, 194),
("GRAY77", 196, 196, 196),
("GRAY78", 199, 199, 199),
("GRAY79", 201, 201, 201),
("GRAY8", 20, 20, 20),
("GRAY80", 204, 204, 204),
("GRAY81", 207, 207, 207),
("GRAY82", 209, 209, 209),
("GRAY83", 212, 212, 212),
("GRAY84", 214, 214, 214),
("GRAY85", 217, 217, 217),
("GRAY86", 219, 219, 219),
("GRAY87", 222, 222, 222),
("GRAY88", 224, 224, 224),
("GRAY89", 227, 227, 227),
("GRAY9", 23, 23, 23),
("GRAY90", 229, 229, 229),
("GRAY91", 232, 232, 232),
("GRAY92", 235, 235, 235),
("GRAY93", 237, 237, 237),
("GRAY94", 240, 240, 240),
("GRAY95", 242, 242, 242),
("GRAY96", 245, 245, 245),
("GRAY97", 247, 247, 247),
("GRAY98", 250, 250, 250),
("GRAY99", 252, 252, 252),
("HONEYDEW", 240, 255, 240),
("HONEYDEW1", 240, 255, 240),
("HONEYDEW2", 224, 238, 224),
("HONEYDEW3", 193, 205, 193),
("HONEYDEW4", 131, 139, 131),
("HOTPINK", 255, 105, 180),
("HOTPINK1", 255, 110, 180),
("HOTPINK2", 238, 106, 167),
("HOTPINK3", 205, 96, 144),
("HOTPINK4", 139, 58, 98),
("INDIANRED", 205, 92, 92),
("INDIANRED1", 255, 106, 106),
("INDIANRED2", 238, 99, 99),
("INDIANRED3", 205, 85, 85),
("INDIANRED4", 139, 58, 58),
("IVORY", 255, 255, 240),
("IVORY1", 255, 255, 240),
("IVORY2", 238, 238, 224),
("IVORY3", 205, 205, 193),
("IVORY4", 139, 139, 131),
("KHAKI", 240, 230, 140),
("KHAKI1", 255, 246, 143),
("KHAKI2", 238, 230, 133),
("KHAKI3", 205, 198, 115),
("KHAKI4", 139, 134, 78),
("LAVENDER", 230, 230, 250),
("LAVENDERBLUSH", 255, 240, 245),
("LAVENDERBLUSH1", 255, 240, 245),
("LAVENDERBLUSH2", 238, 224, 229),
("LAVENDERBLUSH3", 205, 193, 197),
("LAVENDERBLUSH4", 139, 131, 134),
("LAWNGREEN", 124, 252, 0),
("LEMONCHIFFON", 255, 250, 205),
("LEMONCHIFFON1", 255, 250, 205),
("LEMONCHIFFON2", 238, 233, 191),
("LEMONCHIFFON3", 205, 201, 165),
("LEMONCHIFFON4", 139, 137, 112),
("LIGHTBLUE", 173, 216, 230),
("LIGHTBLUE1", 191, 239, 255),
("LIGHTBLUE2", 178, 223, 238),
("LIGHTBLUE3", 154, 192, 205),
("LIGHTBLUE4", 104, 131, 139),
("LIGHTCORAL", 240, 128, 128),
("LIGHTCYAN", 224, 255, 255),
("LIGHTCYAN1", 224, 255, 255),
("LIGHTCYAN2", 209, 238, 238),
("LIGHTCYAN3", 180, 205, 205),
("LIGHTCYAN4", 122, 139, 139),
("LIGHTGOLDENROD", 238, 221, 130),
("LIGHTGOLDENROD1", 255, 236, 139),
("LIGHTGOLDENROD2", 238, 220, 130),
("LIGHTGOLDENROD3", 205, 190, 112),
("LIGHTGOLDENROD4", 139, 129, 76),
("LIGHTGOLDENRODYELLOW", 250, 250, 210),
("LIGHTGREEN", 144, 238, 144),
("LIGHTGRAY", 211, 211, 211),
("LIGHTPINK", 255, 182, 193),
("LIGHTPINK1", 255, 174, 185),
("LIGHTPINK2", 238, 162, 173),
("LIGHTPINK3", 205, 140, 149),
("LIGHTPINK4", 139, 95, 101),
("LIGHTSALMON", 255, 160, 122),
("LIGHTSALMON1", 255, 160, 122),
("LIGHTSALMON2", 238, 149, 114),
("LIGHTSALMON3", 205, 129, 98),
("LIGHTSALMON4", 139, 87, 66),
("LIGHTSEAGREEN", 32, 178, 170),
("LIGHTSKYBLUE", 135, 206, 250),
("LIGHTSKYBLUE1", 176, 226, 255),
("LIGHTSKYBLUE2", 164, 211, 238),
("LIGHTSKYBLUE3", 141, 182, 205),
("LIGHTSKYBLUE4", 96, 123, 139),
("LIGHTSLATEBLUE", 132, 112, 255),
("LIGHTSLATEGRAY", 119, 136, 153),
("LIGHTSTEELBLUE", 176, 196, 222),
("LIGHTSTEELBLUE1", 202, 225, 255),
("LIGHTSTEELBLUE2", 188, 210, 238),
("LIGHTSTEELBLUE3", 162, 181, 205),
("LIGHTSTEELBLUE4", 110, 123, 139),
("LIGHTYELLOW", 255, 255, 224),
("LIGHTYELLOW1", 255, 255, 224),
("LIGHTYELLOW2", 238, 238, 209),
("LIGHTYELLOW3", 205, 205, 180),
("LIGHTYELLOW4", 139, 139, 122),
("LIMEGREEN", 50, 205, 50),
("LINEN", 250, 240, 230),
("MAGENTA", 255, 0, 255),
("MAGENTA1", 255, 0, 255),
("MAGENTA2", 238, 0, 238),
("MAGENTA3", 205, 0, 205),
("MAGENTA4", 139, 0, 139),
("MAROON", 176, 48, 96),
("MAROON1", 255, 52, 179),
("MAROON2", 238, 48, 167),
("MAROON3", 205, 41, 144),
("MAROON4", 139, 28, 98),
("MEDIUMAQUAMARINE", 102, 205, 170),
("MEDIUMBLUE", 0, 0, 205),
("MEDIUMORCHID", 186, 85, 211),
("MEDIUMORCHID1", 224, 102, 255),
("MEDIUMORCHID2", 209, 95, 238),
("MEDIUMORCHID3", 180, 82, 205),
("MEDIUMORCHID4", 122, 55, 139),
("MEDIUMPURPLE", 147, 112, 219),
("MEDIUMPURPLE1", 171, 130, 255),
("MEDIUMPURPLE2", 159, 121, 238),
("MEDIUMPURPLE3", 137, 104, 205),
("MEDIUMPURPLE4", 93, 71, 139),
("MEDIUMSEAGREEN", 60, 179, 113),
("MEDIUMSLATEBLUE", 123, 104, 238),
("MEDIUMSPRINGGREEN", 0, 250, 154),
("MEDIUMTURQUOISE", 72, 209, 204),
("MEDIUMVIOLETRED", 199, 21, 133),
("MIDNIGHTBLUE", 25, 25, 112),
("MINTCREAM", 245, 255, 250),
("MISTYROSE", 255, 228, 225),
("MISTYROSE1", 255, 228, 225),
("MISTYROSE2", 238, 213, 210),
("MISTYROSE3", 205, 183, 181),
("MISTYROSE4", 139, 125, 123),
("MOCCASIN", 255, 228, 181),
("MUPDFBLUE", 37, 114, 172),
("NAVAJOWHITE", 255, 222, 173),
("NAVAJOWHITE1", 255, 222, 173),
("NAVAJOWHITE2", 238, 207, 161),
("NAVAJOWHITE3", 205, 179, 139),
("NAVAJOWHITE4", 139, 121, 94),
("NAVY", 0, 0, 128),
("NAVYBLUE", 0, 0, 128),
("OLDLACE", 253, 245, 230),
("OLIVEDRAB", 107, 142, 35),
("OLIVEDRAB1", 192, 255, 62),
("OLIVEDRAB2", 179, 238, 58),
("OLIVEDRAB3", 154, 205, 50),
("OLIVEDRAB4", 105, 139, 34),
("ORANGE", 255, 165, 0),
("ORANGE1", 255, 165, 0),
("ORANGE2", 238, 154, 0),
("ORANGE3", 205, 133, 0),
("ORANGE4", 139, 90, 0),
("ORANGERED", 255, 69, 0),
("ORANGERED1", 255, 69, 0),
("ORANGERED2", 238, 64, 0),
("ORANGERED3", 205, 55, 0),
("ORANGERED4", 139, 37, 0),
("ORCHID", 218, 112, 214),
("ORCHID1", 255, 131, 250),
("ORCHID2", 238, 122, 233),
("ORCHID3", 205, 105, 201),
("ORCHID4", 139, 71, 137),
("PALEGOLDENROD", 238, 232, 170),
("PALEGREEN", 152, 251, 152),
("PALEGREEN1", 154, 255, 154),
("PALEGREEN2", 144, 238, 144),
("PALEGREEN3", 124, 205, 124),
("PALEGREEN4", 84, 139, 84),
("PALETURQUOISE", 175, 238, 238),
("PALETURQUOISE1", 187, 255, 255),
("PALETURQUOISE2", 174, 238, 238),
("PALETURQUOISE3", 150, 205, 205),
("PALETURQUOISE4", 102, 139, 139),
("PALEVIOLETRED", 219, 112, 147),
("PALEVIOLETRED1", 255, 130, 171),
("PALEVIOLETRED2", 238, 121, 159),
("PALEVIOLETRED3", 205, 104, 137),
("PALEVIOLETRED4", 139, 71, 93),
("PAPAYAWHIP", 255, 239, 213),
("PEACHPUFF", 255, 218, 185),
("PEACHPUFF1", 255, 218, 185),
("PEACHPUFF2", 238, 203, 173),
("PEACHPUFF3", 205, 175, 149),
("PEACHPUFF4", 139, 119, 101),
("PERU", 205, 133, 63),
("PINK", 255, 192, 203),
("PINK1", 255, 181, 197),
("PINK2", 238, 169, 184),
("PINK3", 205, 145, 158),
("PINK4", 139, 99, 108),
("PLUM", 221, 160, 221),
("PLUM1", 255, 187, 255),
("PLUM2", 238, 174, 238),
("PLUM3", 205, 150, 205),
("PLUM4", 139, 102, 139),
("POWDERBLUE", 176, 224, 230),
("PURPLE", 160, 32, 240),
("PURPLE1", 155, 48, 255),
("PURPLE2", 145, 44, 238),
("PURPLE3", 125, 38, 205),
("PURPLE4", 85, 26, 139),
("PY_COLOR", 240, 255, 210),
("RED", 255, 0, 0),
("RED1", 255, 0, 0),
("RED2", 238, 0, 0),
("RED3", 205, 0, 0),
("RED4", 139, 0, 0),
("ROSYBROWN", 188, 143, 143),
("ROSYBROWN1", 255, 193, 193),
("ROSYBROWN2", 238, 180, 180),
("ROSYBROWN3", 205, 155, 155),
("ROSYBROWN4", 139, 105, 105),
("ROYALBLUE", 65, 105, 225),
("ROYALBLUE1", 72, 118, 255),
("ROYALBLUE2", 67, 110, 238),
("ROYALBLUE3", 58, 95, 205),
("ROYALBLUE4", 39, 64, 139),
("SADDLEBROWN", 139, 69, 19),
("SALMON", 250, 128, 114),
("SALMON1", 255, 140, 105),
("SALMON2", 238, 130, 98),
("SALMON3", 205, 112, 84),
("SALMON4", 139, 76, 57),
("SANDYBROWN", 244, 164, 96),
("SEAGREEN", 46, 139, 87),
("SEAGREEN1", 84, 255, 159),
("SEAGREEN2", 78, 238, 148),
("SEAGREEN3", 67, 205, 128),
("SEAGREEN4", 46, 139, 87),
("SEASHELL", 255, 245, 238),
("SEASHELL1", 255, 245, 238),
("SEASHELL2", 238, 229, 222),
("SEASHELL3", 205, 197, 191),
("SEASHELL4", 139, 134, 130),
("SIENNA", 160, 82, 45),
("SIENNA1", 255, 130, 71),
("SIENNA2", 238, 121, 66),
("SIENNA3", 205, 104, 57),
("SIENNA4", 139, 71, 38),
("SKYBLUE", 135, 206, 235),
("SKYBLUE1", 135, 206, 255),
("SKYBLUE2", 126, 192, 238),
("SKYBLUE3", 108, 166, 205),
("SKYBLUE4", 74, 112, 139),
("SLATEBLUE", 106, 90, 205),
("SLATEBLUE1", 131, 111, 255),
("SLATEBLUE2", 122, 103, 238),
("SLATEBLUE3", 105, 89, 205),
("SLATEBLUE4", 71, 60, 139),
("SLATEGRAY", 112, 128, 144),
("SNOW", 255, 250, 250),
("SNOW1", 255, 250, 250),
("SNOW2", 238, 233, 233),
("SNOW3", 205, 201, 201),
("SNOW4", 139, 137, 137),
("SPRINGGREEN", 0, 255, 127),
("SPRINGGREEN1", 0, 255, 127),
("SPRINGGREEN2", 0, 238, 118),
("SPRINGGREEN3", 0, 205, 102),
("SPRINGGREEN4", 0, 139, 69),
("STEELBLUE", 70, 130, 180),
("STEELBLUE1", 99, 184, 255),
("STEELBLUE2", 92, 172, 238),
("STEELBLUE3", 79, 148, 205),
("STEELBLUE4", 54, 100, 139),
("TAN", 210, 180, 140),
("TAN1", 255, 165, 79),
("TAN2", 238, 154, 73),
("TAN3", 205, 133, 63),
("TAN4", 139, 90, 43),
("THISTLE", 216, 191, 216),
("THISTLE1", 255, 225, 255),
("THISTLE2", 238, 210, 238),
("THISTLE3", 205, 181, 205),
("THISTLE4", 139, 123, 139),
("TOMATO", 255, 99, 71),
("TOMATO1", 255, 99, 71),
("TOMATO2", 238, 92, 66),
("TOMATO3", 205, 79, 57),
("TOMATO4", 139, 54, 38),
("TURQUOISE", 64, 224, 208),
("TURQUOISE1", 0, 245, 255),
("TURQUOISE2", 0, 229, 238),
("TURQUOISE3", 0, 197, 205),
("TURQUOISE4", 0, 134, 139),
("VIOLET", 238, 130, 238),
("VIOLETRED", 208, 32, 144),
("VIOLETRED1", 255, 62, 150),
("VIOLETRED2", 238, 58, 140),
("VIOLETRED3", 205, 50, 120),
("VIOLETRED4", 139, 34, 82),
("WHEAT", 245, 222, 179),
("WHEAT1", 255, 231, 186),
("WHEAT2", 238, 216, 174),
("WHEAT3", 205, 186, 150),
("WHEAT4", 139, 126, 102),
("WHITE", 255, 255, 255),
("WHITESMOKE", 245, 245, 245),
("YELLOW", 255, 255, 0),
("YELLOW1", 255, 255, 0),
("YELLOW2", 238, 238, 0),
("YELLOW3", 205, 205, 0),
("YELLOW4", 139, 139, 0),
("YELLOWGREEN", 154, 205, 50),
]
def getColorInfoDict() -> dict:
d = {}
for item in getColorInfoList():
d[item[0].lower()] = item[1:]
return d
def getColor(name: str) -> tuple:
"""Retrieve RGB color in PDF format by name.
Returns:
a triple of floats in range 0 to 1. In case of name-not-found, "white" is returned.
"""
try:
c = getColorInfoList()[getColorList().index(name.upper())]
return (c[1] / 255.0, c[2] / 255.0, c[3] / 255.0)
except Exception:
pymupdf.exception_info()
return (1, 1, 1)
def getColorHSV(name: str) -> tuple:
"""Retrieve the hue, saturation, value triple of a color name.
Returns:
a triple (degree, percent, percent). If not found (-1, -1, -1) is returned.
"""
try:
x = getColorInfoList()[getColorList().index(name.upper())]
except Exception:
if g_exceptions_verbose: pymupdf.exception_info()
return (-1, -1, -1)
r = x[1] / 255.0
g = x[2] / 255.0
b = x[3] / 255.0
cmax = max(r, g, b)
V = round(cmax * 100, 1)
cmin = min(r, g, b)
delta = cmax - cmin
if delta == 0:
hue = 0
elif cmax == r:
hue = 60.0 * (((g - b) / delta) % 6)
elif cmax == g:
hue = 60.0 * (((b - r) / delta) + 2)
else:
hue = 60.0 * (((r - g) / delta) + 4)
H = int(round(hue))
if cmax == 0:
sat = 0
else:
sat = delta / cmax
S = int(round(sat * 100))
return (H, S, V)
def _get_font_properties(doc: pymupdf.Document, xref: int) -> tuple:
fontname, ext, stype, buffer = doc.extract_font(xref)
asc = 0.8
dsc = -0.2
if ext == "":
return fontname, ext, stype, asc, dsc
if buffer:
try:
font = pymupdf.Font(fontbuffer=buffer)
asc = font.ascender
dsc = font.descender
bbox = font.bbox
if asc - dsc < 1:
if bbox.y0 < dsc:
dsc = bbox.y0
asc = 1 - dsc
except Exception:
pymupdf.exception_info()
asc *= 1.2
dsc *= 1.2
return fontname, ext, stype, asc, dsc
if ext != "n/a":
try:
font = pymupdf.Font(fontname)
asc = font.ascender
dsc = font.descender
except Exception:
pymupdf.exception_info()
asc *= 1.2
dsc *= 1.2
else:
asc *= 1.2
dsc *= 1.2
return fontname, ext, stype, asc, dsc
def get_char_widths(
doc: pymupdf.Document, xref: int, limit: int = 256, idx: int = 0, fontdict: OptDict = None
) -> list:
"""Get list of glyph information of a font.
Notes:
Must be provided by its XREF number. If we already dealt with the
font, it will be recorded in doc.FontInfos. Otherwise we insert an
entry there.
Finally we return the glyphs for the font. This is a list of
(glyph, width) where glyph is an integer controlling the char
appearance, and width is a float controlling the char's spacing:
width * fontsize is the actual space.
For 'simple' fonts, glyph == ord(char) will usually be true.
Exceptions are 'Symbol' and 'ZapfDingbats'. We are providing data for these directly here.
"""
fontinfo = pymupdf.CheckFontInfo(doc, xref)
if fontinfo is None: # not recorded yet: create it
if fontdict is None:
name, ext, stype, asc, dsc = _get_font_properties(doc, xref)
fontdict = {
"name": name,
"type": stype,
"ext": ext,
"ascender": asc,
"descender": dsc,
}
else:
name = fontdict["name"]
ext = fontdict["ext"]
stype = fontdict["type"]
ordering = fontdict["ordering"]
simple = fontdict["simple"]
if ext == "":
raise ValueError("xref is not a font")
# check for 'simple' fonts
if stype in ("Type1", "MMType1", "TrueType"):
simple = True
else:
simple = False
# check for CJK fonts
if name in ("Fangti", "Ming"):
ordering = 0
elif name in ("Heiti", "Song"):
ordering = 1
elif name in ("Gothic", "Mincho"):
ordering = 2
elif name in ("Dotum", "Batang"):
ordering = 3
else:
ordering = -1
fontdict["simple"] = simple
if name == "ZapfDingbats":
glyphs = pymupdf.zapf_glyphs
elif name == "Symbol":
glyphs = pymupdf.symbol_glyphs
else:
glyphs = None
fontdict["glyphs"] = glyphs
fontdict["ordering"] = ordering
fontinfo = [xref, fontdict]
doc.FontInfos.append(fontinfo)
else:
fontdict = fontinfo[1]
glyphs = fontdict["glyphs"]
simple = fontdict["simple"]
ordering = fontdict["ordering"]
if glyphs is None:
oldlimit = 0
else:
oldlimit = len(glyphs)
mylimit = max(256, limit)
if mylimit <= oldlimit:
return glyphs
if ordering < 0: # not a CJK font
glyphs = doc._get_char_widths(
xref, fontdict["name"], fontdict["ext"], fontdict["ordering"], mylimit, idx
)
else: # CJK fonts use char codes and width = 1
glyphs = None
fontdict["glyphs"] = glyphs
fontinfo[1] = fontdict
pymupdf.UpdateFontInfo(doc, fontinfo)
return glyphs
class Shape:
"""Create a new shape."""
@staticmethod
def horizontal_angle(C, P):
"""Return the angle to the horizontal for the connection from C to P.
This uses the arcus sine function and resolves its inherent ambiguity by
looking up in which quadrant vector S = P - C is located.
"""
S = pymupdf.Point(P - C).unit # unit vector 'C' -> 'P'
alfa = math.asin(abs(S.y)) # absolute angle from horizontal
if S.x < 0: # make arcsin result unique
if S.y <= 0: # bottom-left
alfa = -(math.pi - alfa)
else: # top-left
alfa = math.pi - alfa
else:
if S.y >= 0: # top-right
pass
else: # bottom-right
alfa = -alfa
return alfa
def __init__(self, page: pymupdf.Page):
pymupdf.CheckParent(page)
self.page = page
self.doc = page.parent
if not self.doc.is_pdf:
raise ValueError("is no PDF")
self.height = page.mediabox_size.y
self.width = page.mediabox_size.x
self.x = page.cropbox_position.x
self.y = page.cropbox_position.y
self.pctm = page.transformation_matrix # page transf. matrix
self.ipctm = ~self.pctm # inverted transf. matrix
self.draw_cont = ""
self.text_cont = ""
self.totalcont = ""
self.last_point = None
self.rect = None
def updateRect(self, x):
if self.rect is None:
if len(x) == 2:
self.rect = pymupdf.Rect(x, x)
else:
self.rect = pymupdf.Rect(x)
else:
if len(x) == 2:
x = pymupdf.Point(x)
self.rect.x0 = min(self.rect.x0, x.x)
self.rect.y0 = min(self.rect.y0, x.y)
self.rect.x1 = max(self.rect.x1, x.x)
self.rect.y1 = max(self.rect.y1, x.y)
else:
x = pymupdf.Rect(x)
self.rect.x0 = min(self.rect.x0, x.x0)
self.rect.y0 = min(self.rect.y0, x.y0)
self.rect.x1 = max(self.rect.x1, x.x1)
self.rect.y1 = max(self.rect.y1, x.y1)
def draw_line(self, p1: point_like, p2: point_like) -> pymupdf.Point:
"""Draw a line between two points."""
p1 = pymupdf.Point(p1)
p2 = pymupdf.Point(p2)
if not (self.last_point == p1):
self.draw_cont += _format_g(pymupdf.JM_TUPLE(p1 * self.ipctm)) + " m\n"
self.last_point = p1
self.updateRect(p1)
self.draw_cont += _format_g(pymupdf.JM_TUPLE(p2 * self.ipctm)) + " l\n"
self.updateRect(p2)
self.last_point = p2
return self.last_point
def draw_polyline(self, points: list) -> pymupdf.Point:
"""Draw several connected line segments."""
for i, p in enumerate(points):
if i == 0:
if not (self.last_point == pymupdf.Point(p)):
self.draw_cont += _format_g(pymupdf.JM_TUPLE(pymupdf.Point(p) * self.ipctm)) + " m\n"
self.last_point = pymupdf.Point(p)
else:
self.draw_cont += _format_g(pymupdf.JM_TUPLE(pymupdf.Point(p) * self.ipctm)) + " l\n"
self.updateRect(p)
self.last_point = pymupdf.Point(points[-1])
return self.last_point
def draw_bezier(
self,
p1: point_like,
p2: point_like,
p3: point_like,
p4: point_like,
) -> pymupdf.Point:
"""Draw a standard cubic Bezier curve."""
p1 = pymupdf.Point(p1)
p2 = pymupdf.Point(p2)
p3 = pymupdf.Point(p3)
p4 = pymupdf.Point(p4)
if not (self.last_point == p1):
self.draw_cont += _format_g(pymupdf.JM_TUPLE(p1 * self.ipctm)) + " m\n"
args = pymupdf.JM_TUPLE(list(p2 * self.ipctm) + list(p3 * self.ipctm) + list(p4 * self.ipctm))
self.draw_cont += _format_g(args) + " c\n"
self.updateRect(p1)
self.updateRect(p2)
self.updateRect(p3)
self.updateRect(p4)
self.last_point = p4
return self.last_point
def draw_oval(self, tetra: typing.Union[quad_like, rect_like]) -> pymupdf.Point:
"""Draw an ellipse inside a tetrapod."""
if len(tetra) != 4:
raise ValueError("invalid arg length")
if hasattr(tetra[0], "__float__"):
q = pymupdf.Rect(tetra).quad
else:
q = pymupdf.Quad(tetra)
mt = q.ul + (q.ur - q.ul) * 0.5
mr = q.ur + (q.lr - q.ur) * 0.5
mb = q.ll + (q.lr - q.ll) * 0.5
ml = q.ul + (q.ll - q.ul) * 0.5
if not (self.last_point == ml):
self.draw_cont += _format_g(pymupdf.JM_TUPLE(ml * self.ipctm)) + " m\n"
self.last_point = ml
self.draw_curve(ml, q.ll, mb)
self.draw_curve(mb, q.lr, mr)
self.draw_curve(mr, q.ur, mt)
self.draw_curve(mt, q.ul, ml)
self.updateRect(q.rect)
self.last_point = ml
return self.last_point
def draw_circle(self, center: point_like, radius: float) -> pymupdf.Point:
"""Draw a circle given its center and radius."""
if not radius > pymupdf.EPSILON:
raise ValueError("radius must be positive")
center = pymupdf.Point(center)
p1 = center - (radius, 0)
return self.draw_sector(center, p1, 360, fullSector=False)
def draw_curve(
self,
p1: point_like,
p2: point_like,
p3: point_like,
) -> pymupdf.Point:
"""Draw a curve between points using one control point."""
kappa = 0.55228474983
p1 = pymupdf.Point(p1)
p2 = pymupdf.Point(p2)
p3 = pymupdf.Point(p3)
k1 = p1 + (p2 - p1) * kappa
k2 = p3 + (p2 - p3) * kappa
return self.draw_bezier(p1, k1, k2, p3)
def draw_sector(
self,
center: point_like,
point: point_like,
beta: float,
fullSector: bool = True,
) -> pymupdf.Point:
"""Draw a circle sector."""
center = pymupdf.Point(center)
point = pymupdf.Point(point)
l3 = lambda a, b: _format_g((a, b)) + " m\n"
l4 = lambda a, b, c, d, e, f: _format_g((a, b, c, d, e, f)) + " c\n"
l5 = lambda a, b: _format_g((a, b)) + " l\n"
betar = math.radians(-beta)
w360 = math.radians(math.copysign(360, betar)) * (-1)
w90 = math.radians(math.copysign(90, betar))
w45 = w90 / 2
while abs(betar) > 2 * math.pi:
betar += w360 # bring angle below 360 degrees
if not (self.last_point == point):
self.draw_cont += l3(*pymupdf.JM_TUPLE(point * self.ipctm))
self.last_point = point
Q = pymupdf.Point(0, 0) # just make sure it exists
C = center
P = point
S = P - C # vector 'center' -> 'point'
rad = abs(S) # circle radius
if not rad > pymupdf.EPSILON:
raise ValueError("radius must be positive")
alfa = self.horizontal_angle(center, point)
while abs(betar) > abs(w90): # draw 90 degree arcs
q1 = C.x + math.cos(alfa + w90) * rad
q2 = C.y + math.sin(alfa + w90) * rad
Q = pymupdf.Point(q1, q2) # the arc's end point
r1 = C.x + math.cos(alfa + w45) * rad / math.cos(w45)
r2 = C.y + math.sin(alfa + w45) * rad / math.cos(w45)
R = pymupdf.Point(r1, r2) # crossing point of tangents
kappah = (1 - math.cos(w45)) * 4 / 3 / abs(R - Q)
kappa = kappah * abs(P - Q)
cp1 = P + (R - P) * kappa # control point 1
cp2 = Q + (R - Q) * kappa # control point 2
self.draw_cont += l4(*pymupdf.JM_TUPLE(
list(cp1 * self.ipctm) + list(cp2 * self.ipctm) + list(Q * self.ipctm)
))
betar -= w90 # reduce param angle by 90 deg
alfa += w90 # advance start angle by 90 deg
P = Q # advance to arc end point
# draw (remaining) arc
if abs(betar) > 1e-3: # significant degrees left?
beta2 = betar / 2
q1 = C.x + math.cos(alfa + betar) * rad
q2 = C.y + math.sin(alfa + betar) * rad
Q = pymupdf.Point(q1, q2) # the arc's end point
r1 = C.x + math.cos(alfa + beta2) * rad / math.cos(beta2)
r2 = C.y + math.sin(alfa + beta2) * rad / math.cos(beta2)
R = pymupdf.Point(r1, r2) # crossing point of tangents
# kappa height is 4/3 of segment height
kappah = (1 - math.cos(beta2)) * 4 / 3 / abs(R - Q) # kappa height
kappa = kappah * abs(P - Q) / (1 - math.cos(betar))
cp1 = P + (R - P) * kappa # control point 1
cp2 = Q + (R - Q) * kappa # control point 2
self.draw_cont += l4(*pymupdf.JM_TUPLE(
list(cp1 * self.ipctm) + list(cp2 * self.ipctm) + list(Q * self.ipctm)
))
if fullSector:
self.draw_cont += l3(*pymupdf.JM_TUPLE(point * self.ipctm))
self.draw_cont += l5(*pymupdf.JM_TUPLE(center * self.ipctm))
self.draw_cont += l5(*pymupdf.JM_TUPLE(Q * self.ipctm))
self.last_point = Q
return self.last_point
def draw_rect(self, rect: rect_like, *, radius=None) -> pymupdf.Point:
"""Draw a rectangle.
Args:
radius: if not None, the rectangle will have rounded corners.
This is the radius of the curvature, given as percentage of
the rectangle width or height. Valid are values 0 < v <= 0.5.
For a sequence of two values, the corners will have different
radii. Otherwise, the percentage will be computed from the
shorter side. A value of (0.5, 0.5) will draw an ellipse.
"""
r = pymupdf.Rect(rect)
if radius is None: # standard rectangle
self.draw_cont += _format_g(pymupdf.JM_TUPLE(
list(r.bl * self.ipctm) + [r.width, r.height]
)) + " re\n"
self.updateRect(r)
self.last_point = r.tl
return self.last_point
# rounded corners requested. This requires 1 or 2 values, each
# with 0 < value <= 0.5
if hasattr(radius, "__float__"):
if radius <= 0 or radius > 0.5:
raise ValueError(f"bad radius value {radius}.")
d = min(r.width, r.height) * radius
px = (d, 0)
py = (0, d)
elif hasattr(radius, "__len__") and len(radius) == 2:
rx, ry = radius
px = (rx * r.width, 0)
py = (0, ry * r.height)
if min(rx, ry) <= 0 or max(rx, ry) > 0.5:
raise ValueError(f"bad radius value {radius}.")
else:
raise ValueError(f"bad radius value {radius}.")
lp = self.draw_line(r.tl + py, r.bl - py)
lp = self.draw_curve(lp, r.bl, r.bl + px)
lp = self.draw_line(lp, r.br - px)
lp = self.draw_curve(lp, r.br, r.br - py)
lp = self.draw_line(lp, r.tr + py)
lp = self.draw_curve(lp, r.tr, r.tr - px)
lp = self.draw_line(lp, r.tl + px)
self.last_point = self.draw_curve(lp, r.tl, r.tl + py)
self.updateRect(r)
return self.last_point
def draw_quad(self, quad: quad_like) -> pymupdf.Point:
"""Draw a Quad."""
q = pymupdf.Quad(quad)
return self.draw_polyline([q.ul, q.ll, q.lr, q.ur, q.ul])
def draw_zigzag(
self,
p1: point_like,
p2: point_like,
breadth: float = 2,
) -> pymupdf.Point:
"""Draw a zig-zagged line from p1 to p2."""
p1 = pymupdf.Point(p1)
p2 = pymupdf.Point(p2)
S = p2 - p1 # vector start - end
rad = abs(S) # distance of points
cnt = 4 * int(round(rad / (4 * breadth), 0)) # always take full phases
if cnt < 4:
raise ValueError("points too close")
mb = rad / cnt # revised breadth
matrix = pymupdf.Matrix(pymupdf.util_hor_matrix(p1, p2)) # normalize line to x-axis
i_mat = ~matrix # get original position
points = [] # stores edges
for i in range(1, cnt):
if i % 4 == 1: # point "above" connection
p = pymupdf.Point(i, -1) * mb
elif i % 4 == 3: # point "below" connection
p = pymupdf.Point(i, 1) * mb
else: # ignore others
continue
points.append(p * i_mat)
self.draw_polyline([p1] + points + [p2]) # add start and end points
return p2
def draw_squiggle(
self,
p1: point_like,
p2: point_like,
breadth=2,
) -> pymupdf.Point:
"""Draw a squiggly line from p1 to p2."""
p1 = pymupdf.Point(p1)
p2 = pymupdf.Point(p2)
S = p2 - p1 # vector start - end
rad = abs(S) # distance of points
cnt = 4 * int(round(rad / (4 * breadth), 0)) # always take full phases
if cnt < 4:
raise ValueError("points too close")
mb = rad / cnt # revised breadth
matrix = pymupdf.Matrix(pymupdf.util_hor_matrix(p1, p2)) # normalize line to x-axis
i_mat = ~matrix # get original position
k = 2.4142135623765633 # y of draw_curve helper point
points = [] # stores edges
for i in range(1, cnt):
if i % 4 == 1: # point "above" connection
p = pymupdf.Point(i, -k) * mb
elif i % 4 == 3: # point "below" connection
p = pymupdf.Point(i, k) * mb
else: # else on connection line
p = pymupdf.Point(i, 0) * mb
points.append(p * i_mat)
points = [p1] + points + [p2]
cnt = len(points)
i = 0
while i + 2 < cnt:
self.draw_curve(points[i], points[i + 1], points[i + 2])
i += 2
return p2
# ==============================================================================
# Shape.insert_text
# ==============================================================================
def insert_text(
self,
point: point_like,
buffer: typing.Union[str, list],
fontsize: float = 11,
lineheight: OptFloat = None,
fontname: str = "helv",
fontfile: OptStr = None,
set_simple: bool = 0,
encoding: int = 0,
color: OptSeq = None,
fill: OptSeq = None,
render_mode: int = 0,
border_width: float = 0.05,
rotate: int = 0,
morph: OptSeq = None,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> int:
# ensure 'text' is a list of strings, worth dealing with
if not bool(buffer):
return 0
if type(buffer) not in (list, tuple):
text = buffer.splitlines()
else:
text = buffer
if not len(text) > 0:
return 0
point = pymupdf.Point(point)
try:
maxcode = max([ord(c) for c in " ".join(text)])
except Exception:
pymupdf.exception_info()
return 0
# ensure valid 'fontname'
fname = fontname
if fname.startswith("/"):
fname = fname[1:]
xref = self.page.insert_font(
fontname=fname, fontfile=fontfile, encoding=encoding, set_simple=set_simple
)
fontinfo = pymupdf.CheckFontInfo(self.doc, xref)
fontdict = fontinfo[1]
ordering = fontdict["ordering"]
simple = fontdict["simple"]
bfname = fontdict["name"]
ascender = fontdict["ascender"]
descender = fontdict["descender"]
if lineheight:
lheight = fontsize * lineheight
elif ascender - descender <= 1:
lheight = fontsize * 1.2
else:
lheight = fontsize * (ascender - descender)
if maxcode > 255:
glyphs = self.doc.get_char_widths(xref, maxcode + 1)
else:
glyphs = fontdict["glyphs"]
tab = []
for t in text:
if simple and bfname not in ("Symbol", "ZapfDingbats"):
g = None
else:
g = glyphs
tab.append(pymupdf.getTJstr(t, g, simple, ordering))
text = tab
color_str = pymupdf.ColorCode(color, "c")
fill_str = pymupdf.ColorCode(fill, "f")
if not fill and render_mode == 0: # ensure fill color when 0 Tr
fill = color
fill_str = pymupdf.ColorCode(color, "f")
morphing = pymupdf.CheckMorph(morph)
rot = rotate
if rot % 90 != 0:
raise ValueError("bad rotate value")
while rot < 0:
rot += 360
rot = rot % 360 # text rotate = 0, 90, 270, 180
templ1 = lambda a, b, c, d, e, f, g: f"\nq\n{a}{b}BT\n{c}1 0 0 1 {_format_g((d, e))} Tm\n/{f} {_format_g(g)} Tf "
templ2 = lambda a: f"TJ\n0 -{_format_g(a)} TD\n"
cmp90 = "0 1 -1 0 0 0 cm\n" # rotates 90 deg counter-clockwise
cmm90 = "0 -1 1 0 0 0 cm\n" # rotates 90 deg clockwise
cm180 = "-1 0 0 -1 0 0 cm\n" # rotates by 180 deg.
height = self.height
width = self.width
# setting up for standard rotation directions
# case rotate = 0
if morphing:
m1 = pymupdf.Matrix(1, 0, 0, 1, morph[0].x + self.x, height - morph[0].y - self.y)
mat = ~m1 * morph[1] * m1
cm = _format_g(pymupdf.JM_TUPLE(mat)) + " cm\n"
else:
cm = ""
top = height - point.y - self.y # start of 1st char
left = point.x + self.x # start of 1. char
space = top # space available
#headroom = point.y + self.y # distance to page border
if rot == 90:
left = height - point.y - self.y
top = -point.x - self.x
cm += cmp90
space = width - abs(top)
#headroom = point.x + self.x
elif rot == 270:
left = -height + point.y + self.y
top = point.x + self.x
cm += cmm90
space = abs(top)
#headroom = width - point.x - self.x
elif rot == 180:
left = -point.x - self.x
top = -height + point.y + self.y
cm += cm180
space = abs(point.y + self.y)
#headroom = height - point.y - self.y
optcont = self.page._get_optional_content(oc)
if optcont is not None:
bdc = "/OC /%s BDC\n" % optcont
emc = "EMC\n"
else:
bdc = emc = ""
alpha = self.page._set_opacity(CA=stroke_opacity, ca=fill_opacity)
if alpha is None:
alpha = ""
else:
alpha = "/%s gs\n" % alpha
nres = templ1(bdc, alpha, cm, left, top, fname, fontsize)
if render_mode > 0:
nres += "%i Tr " % render_mode
nres += _format_g(border_width * fontsize) + " w "
if color is not None:
nres += color_str
if fill is not None:
nres += fill_str
# =========================================================================
# start text insertion
# =========================================================================
nres += text[0]
nlines = 1 # set output line counter
if len(text) > 1:
nres += templ2(lheight) # line 1
else:
nres += 'TJ'
for i in range(1, len(text)):
if space < lheight:
break # no space left on page
if i > 1:
nres += "\nT* "
nres += text[i] + 'TJ'
space -= lheight
nlines += 1
nres += "\nET\n%sQ\n" % emc
# =========================================================================
# end of text insertion
# =========================================================================
# update the /Contents object
self.text_cont += nres
return nlines
# ==============================================================================
# Shape.insert_textbox
# ==============================================================================
def insert_textbox(
self,
rect: rect_like,
buffer: typing.Union[str, list],
fontname: OptStr = "helv",
fontfile: OptStr = None,
fontsize: float = 11,
lineheight: OptFloat = None,
set_simple: bool = 0,
encoding: int = 0,
color: OptSeq = None,
fill: OptSeq = None,
expandtabs: int = 1,
border_width: float = 0.05,
align: int = 0,
render_mode: int = 0,
rotate: int = 0,
morph: OptSeq = None,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> float:
"""Insert text into a given rectangle.
Args:
rect -- the textbox to fill
buffer -- text to be inserted
fontname -- a Base-14 font, font name or '/name'
fontfile -- name of a font file
fontsize -- font size
lineheight -- overwrite the font property
color -- RGB stroke color triple
fill -- RGB fill color triple
render_mode -- text rendering control
border_width -- thickness of glyph borders as percentage of fontsize
expandtabs -- handles tabulators with string function
align -- left, center, right, justified
rotate -- 0, 90, 180, or 270 degrees
morph -- morph box with a matrix and a fixpoint
Returns:
unused or deficit rectangle area (float)
"""
rect = pymupdf.Rect(rect)
if rect.is_empty or rect.is_infinite:
raise ValueError("text box must be finite and not empty")
color_str = pymupdf.ColorCode(color, "c")
fill_str = pymupdf.ColorCode(fill, "f")
if fill is None and render_mode == 0: # ensure fill color for 0 Tr
fill = color
fill_str = pymupdf.ColorCode(color, "f")
optcont = self.page._get_optional_content(oc)
if optcont is not None:
bdc = "/OC /%s BDC\n" % optcont
emc = "EMC\n"
else:
bdc = emc = ""
# determine opacity / transparency
alpha = self.page._set_opacity(CA=stroke_opacity, ca=fill_opacity)
if alpha is None:
alpha = ""
else:
alpha = "/%s gs\n" % alpha
if rotate % 90 != 0:
raise ValueError("rotate must be multiple of 90")
rot = rotate
while rot < 0:
rot += 360
rot = rot % 360
# is buffer worth of dealing with?
if not bool(buffer):
return rect.height if rot in (0, 180) else rect.width
cmp90 = "0 1 -1 0 0 0 cm\n" # rotates counter-clockwise
cmm90 = "0 -1 1 0 0 0 cm\n" # rotates clockwise
cm180 = "-1 0 0 -1 0 0 cm\n" # rotates by 180 deg.
height = self.height
fname = fontname
if fname.startswith("/"):
fname = fname[1:]
xref = self.page.insert_font(
fontname=fname, fontfile=fontfile, encoding=encoding, set_simple=set_simple
)
fontinfo = pymupdf.CheckFontInfo(self.doc, xref)
fontdict = fontinfo[1]
ordering = fontdict["ordering"]
simple = fontdict["simple"]
glyphs = fontdict["glyphs"]
bfname = fontdict["name"]
ascender = fontdict["ascender"]
descender = fontdict["descender"]
if lineheight:
lheight_factor = lineheight
elif ascender - descender <= 1:
lheight_factor = 1.2
else:
lheight_factor = ascender - descender
lheight = fontsize * lheight_factor
# create a list from buffer, split into its lines
if type(buffer) in (list, tuple):
t0 = "\n".join(buffer)
else:
t0 = buffer
maxcode = max([ord(c) for c in t0])
# replace invalid char codes for simple fonts
if simple and maxcode > 255:
t0 = "".join([c if ord(c) < 256 else "?" for c in t0])
t0 = t0.splitlines()
glyphs = self.doc.get_char_widths(xref, maxcode + 1)
if simple and bfname not in ("Symbol", "ZapfDingbats"):
tj_glyphs = None
else:
tj_glyphs = glyphs
# ----------------------------------------------------------------------
# calculate pixel length of a string
# ----------------------------------------------------------------------
def pixlen(x):
"""Calculate pixel length of x."""
if ordering < 0:
return sum([glyphs[ord(c)][1] for c in x]) * fontsize
else:
return len(x) * fontsize
# ---------------------------------------------------------------------
if ordering < 0:
blen = glyphs[32][1] * fontsize # pixel size of space character
else:
blen = fontsize
text = "" # output buffer
if pymupdf.CheckMorph(morph):
m1 = pymupdf.Matrix(
1, 0, 0, 1, morph[0].x + self.x, self.height - morph[0].y - self.y
)
mat = ~m1 * morph[1] * m1
cm = _format_g(pymupdf.JM_TUPLE(mat)) + " cm\n"
else:
cm = ""
# ---------------------------------------------------------------------
# adjust for text orientation / rotation
# ---------------------------------------------------------------------
progr = 1 # direction of line progress
c_pnt = pymupdf.Point(0, fontsize * ascender) # used for line progress
if rot == 0: # normal orientation
point = rect.tl + c_pnt # line 1 is 'lheight' below top
maxwidth = rect.width # pixels available in one line
maxheight = rect.height # available text height
elif rot == 90: # rotate counter clockwise
c_pnt = pymupdf.Point(fontsize * ascender, 0) # progress in x-direction
point = rect.bl + c_pnt # line 1 'lheight' away from left
maxwidth = rect.height # pixels available in one line
maxheight = rect.width # available text height
cm += cmp90
elif rot == 180: # text upside down
# progress upwards in y direction
c_pnt = -pymupdf.Point(0, fontsize * ascender)
point = rect.br + c_pnt # line 1 'lheight' above bottom
maxwidth = rect.width # pixels available in one line
progr = -1 # subtract lheight for next line
maxheight =rect.height # available text height
cm += cm180
else: # rotate clockwise (270 or -90)
# progress from right to left
c_pnt = -pymupdf.Point(fontsize * ascender, 0)
point = rect.tr + c_pnt # line 1 'lheight' left of right
maxwidth = rect.height # pixels available in one line
progr = -1 # subtract lheight for next line
maxheight = rect.width # available text height
cm += cmm90
# =====================================================================
# line loop
# =====================================================================
just_tab = [] # 'justify' indicators per line
for i, line in enumerate(t0):
line_t = line.expandtabs(expandtabs).split(" ") # split into words
num_words = len(line_t)
lbuff = "" # init line buffer
rest = maxwidth # available line pixels
# =================================================================
# word loop
# =================================================================
for j in range(num_words):
word = line_t[j]
pl_w = pixlen(word) # pixel len of word
if rest >= pl_w: # does it fit on the line?
lbuff += word + " " # yes, append word
rest -= pl_w + blen # update available line space
continue # next word
# word doesn't fit - output line (if not empty)
if lbuff:
lbuff = lbuff.rstrip() + "\n" # line full, append line break
text += lbuff # append to total text
just_tab.append(True) # can align-justify
lbuff = "" # re-init line buffer
rest = maxwidth # re-init avail. space
if pl_w <= maxwidth: # word shorter than 1 line?
lbuff = word + " " # start the line with it
rest = maxwidth - pl_w - blen # update free space
continue
# long word: split across multiple lines - char by char ...
if len(just_tab) > 0:
just_tab[-1] = False # cannot align-justify
for c in word:
if pixlen(lbuff) <= maxwidth - pixlen(c):
lbuff += c
else: # line full
lbuff += "\n" # close line
text += lbuff # append to text
just_tab.append(False) # cannot align-justify
lbuff = c # start new line with this char
lbuff += " " # finish long word
rest = maxwidth - pixlen(lbuff) # long word stored
if lbuff: # unprocessed line content?
text += lbuff.rstrip() # append to text
just_tab.append(False) # cannot align-justify
if i < len(t0) - 1: # not the last line?
text += "\n" # insert line break
# compute used part of the textbox
if text.endswith("\n"):
text = text[:-1]
lb_count = text.count("\n") + 1 # number of lines written
# text height = line count * line height plus one descender value
text_height = lheight * lb_count - descender * fontsize
more = text_height - maxheight # difference to height limit
if more > pymupdf.EPSILON: # landed too much outside rect
return (-1) * more # return deficit, don't output
more = abs(more)
if more < pymupdf.EPSILON:
more = 0 # don't bother with epsilons
nres = "\nq\n%s%sBT\n" % (bdc, alpha) + cm # initialize output buffer
templ = lambda a, b, c, d: f"1 0 0 1 {_format_g((a, b))} Tm /{c} {_format_g(d)} Tf "
# center, right, justify: output each line with its own specifics
text_t = text.splitlines() # split text in lines again
just_tab[-1] = False # never justify last line
for i, t in enumerate(text_t):
spacing = 0
pl = maxwidth - pixlen(t) # length of empty line part
pnt = point + c_pnt * (i * lheight_factor) # text start of line
if align == 1: # center: right shift by half width
if rot in (0, 180):
pnt = pnt + pymupdf.Point(pl / 2, 0) * progr
else:
pnt = pnt - pymupdf.Point(0, pl / 2) * progr
elif align == 2: # right: right shift by full width
if rot in (0, 180):
pnt = pnt + pymupdf.Point(pl, 0) * progr
else:
pnt = pnt - pymupdf.Point(0, pl) * progr
elif align == 3: # justify
spaces = t.count(" ") # number of spaces in line
if spaces > 0 and just_tab[i]: # if any, and we may justify
spacing = pl / spaces # make every space this much larger
else:
spacing = 0 # keep normal space length
top = height - pnt.y - self.y
left = pnt.x + self.x
if rot == 90:
left = height - pnt.y - self.y
top = -pnt.x - self.x
elif rot == 270:
left = -height + pnt.y + self.y
top = pnt.x + self.x
elif rot == 180:
left = -pnt.x - self.x
top = -height + pnt.y + self.y
nres += templ(left, top, fname, fontsize)
if render_mode > 0:
nres += "%i Tr " % render_mode
nres += _format_g(border_width * fontsize) + " w "
if align == 3:
nres += _format_g(spacing) + " Tw "
if color is not None:
nres += color_str
if fill is not None:
nres += fill_str
nres += "%sTJ\n" % pymupdf.getTJstr(t, tj_glyphs, simple, ordering)
nres += "ET\n%sQ\n" % emc
self.text_cont += nres
self.updateRect(rect)
return more
def finish(
self,
width: float = 1,
color: OptSeq = (0,),
fill: OptSeq = None,
lineCap: int = 0,
lineJoin: int = 0,
dashes: OptStr = None,
even_odd: bool = False,
morph: OptSeq = None,
closePath: bool = True,
fill_opacity: float = 1,
stroke_opacity: float = 1,
oc: int = 0,
) -> None:
"""Finish the current drawing segment.
Notes:
Apply colors, opacity, dashes, line style and width, or
morphing. Also whether to close the path
by connecting last to first point.
"""
if self.draw_cont == "": # treat empty contents as no-op
return
if width == 0: # border color makes no sense then
color = None
elif color is None: # vice versa
width = 0
# if color == None and fill == None:
# raise ValueError("at least one of 'color' or 'fill' must be given")
color_str = pymupdf.ColorCode(color, "c") # ensure proper color string
fill_str = pymupdf.ColorCode(fill, "f") # ensure proper fill string
optcont = self.page._get_optional_content(oc)
if optcont is not None:
self.draw_cont = "/OC /%s BDC\n" % optcont + self.draw_cont
emc = "EMC\n"
else:
emc = ""
alpha = self.page._set_opacity(CA=stroke_opacity, ca=fill_opacity)
if alpha is not None:
self.draw_cont = "/%s gs\n" % alpha + self.draw_cont
if width != 1 and width != 0:
self.draw_cont += _format_g(width) + " w\n"
if lineCap != 0:
self.draw_cont = "%i J\n" % lineCap + self.draw_cont
if lineJoin != 0:
self.draw_cont = "%i j\n" % lineJoin + self.draw_cont
if dashes not in (None, "", "[] 0"):
self.draw_cont = "%s d\n" % dashes + self.draw_cont
if closePath:
self.draw_cont += "h\n"
self.last_point = None
if color is not None:
self.draw_cont += color_str
if fill is not None:
self.draw_cont += fill_str
if color is not None:
if not even_odd:
self.draw_cont += "B\n"
else:
self.draw_cont += "B*\n"
else:
if not even_odd:
self.draw_cont += "f\n"
else:
self.draw_cont += "f*\n"
else:
self.draw_cont += "S\n"
self.draw_cont += emc
if pymupdf.CheckMorph(morph):
m1 = pymupdf.Matrix(
1, 0, 0, 1, morph[0].x + self.x, self.height - morph[0].y - self.y
)
mat = ~m1 * morph[1] * m1
self.draw_cont = _format_g(pymupdf.JM_TUPLE(mat)) + " cm\n" + self.draw_cont
self.totalcont += "\nq\n" + self.draw_cont + "Q\n"
self.draw_cont = ""
self.last_point = None
return
def commit(self, overlay: bool = True) -> None:
"""Update the page's /Contents object with Shape data.
The argument controls whether data appear in foreground (default)
or background.
"""
pymupdf.CheckParent(self.page) # doc may have died meanwhile
self.totalcont += self.text_cont
self.totalcont = self.totalcont.encode()
if self.totalcont:
if overlay:
self.page.wrap_contents() # ensure a balanced graphics state
# make /Contents object with dummy stream
xref = pymupdf.TOOLS._insert_contents(self.page, b" ", overlay)
# update it with potential compression
self.doc.update_stream(xref, self.totalcont)
self.last_point = None # clean up ...
self.rect = None #
self.draw_cont = "" # for potential ...
self.text_cont = "" # ...
self.totalcont = "" # re-use
def apply_redactions(
page: pymupdf.Page, images: int = 2, graphics: int = 1, text: int = 0
) -> bool:
"""Apply the redaction annotations of the page.
Args:
page: the PDF page.
images:
0 - ignore images
1 - remove all overlapping images
2 - blank out overlapping image parts
3 - remove image unless invisible
graphics:
0 - ignore graphics
1 - remove graphics if contained in rectangle
2 - remove all overlapping graphics
text:
0 - remove text
1 - ignore text
"""
def center_rect(annot_rect, new_text, font, fsize):
"""Calculate minimal sub-rectangle for the overlay text.
Notes:
Because 'insert_textbox' supports no vertical text centering,
we calculate an approximate number of lines here and return a
sub-rect with smaller height, which should still be sufficient.
Args:
annot_rect: the annotation rectangle
new_text: the text to insert.
font: the fontname. Must be one of the CJK or Base-14 set, else
the rectangle is returned unchanged.
fsize: the fontsize
Returns:
A rectangle to use instead of the annot rectangle.
"""
exception_types = (ValueError, mupdf.FzErrorBase)
if pymupdf.mupdf_version_tuple < (1, 24):
exception_types = ValueError
if not new_text or annot_rect.width <= pymupdf.EPSILON:
return annot_rect
try:
text_width = pymupdf.get_text_length(new_text, font, fsize)
except exception_types: # unsupported font
if g_exceptions_verbose:
pymupdf.exception_info()
return annot_rect
line_height = fsize * 1.2
limit = annot_rect.width
h = math.ceil(text_width / limit) * line_height # estimate rect height
if h >= annot_rect.height:
return annot_rect
r = annot_rect
y = (annot_rect.tl.y + annot_rect.bl.y - h) * 0.5
r.y0 = y
return r
pymupdf.CheckParent(page)
doc = page.parent
if doc.is_encrypted or doc.is_closed:
raise ValueError("document closed or encrypted")
if not doc.is_pdf:
raise ValueError("is no PDF")
redact_annots = [] # storage of annot values
for annot in page.annots(
types=(pymupdf.PDF_ANNOT_REDACT,) # pylint: disable=no-member
):
# loop redactions
redact_annots.append(annot._get_redact_values()) # save annot values
if redact_annots == []: # any redactions on this page?
return False # no redactions
rc = page._apply_redactions(text, images, graphics) # call MuPDF
if not rc: # should not happen really
raise ValueError("Error applying redactions.")
# now write replacement text in old redact rectangles
shape = page.new_shape()
for redact in redact_annots:
annot_rect = redact["rect"]
fill = redact["fill"]
if fill:
shape.draw_rect(annot_rect) # colorize the rect background
shape.finish(fill=fill, color=fill)
if "text" in redact.keys(): # if we also have text
new_text = redact["text"]
align = redact.get("align", 0)
fname = redact["fontname"]
fsize = redact["fontsize"]
color = redact["text_color"]
# try finding vertical centered sub-rect
trect = center_rect(annot_rect, new_text, fname, fsize)
rc = -1
while rc < 0 and fsize >= 4: # while not enough room
# (re-) try insertion
rc = shape.insert_textbox(
trect,
new_text,
fontname=fname,
fontsize=fsize,
color=color,
align=align,
)
fsize -= 0.5 # reduce font if unsuccessful
shape.commit() # append new contents object
return True
# ------------------------------------------------------------------------------
# Remove potentially sensitive data from a PDF. Similar to the Adobe
# Acrobat 'sanitize' function
# ------------------------------------------------------------------------------
def scrub(
doc: pymupdf.Document,
attached_files: bool = True,
clean_pages: bool = True,
embedded_files: bool = True,
hidden_text: bool = True,
javascript: bool = True,
metadata: bool = True,
redactions: bool = True,
redact_images: int = 0,
remove_links: bool = True,
reset_fields: bool = True,
reset_responses: bool = True,
thumbnails: bool = True,
xml_metadata: bool = True,
) -> None:
def remove_hidden(cont_lines):
"""Remove hidden text from a PDF page.
Args:
cont_lines: list of lines with /Contents content. Should have status
from after page.cleanContents().
Returns:
List of /Contents lines from which hidden text has been removed.
Notes:
The input must have been created after the page's /Contents object(s)
have been cleaned with page.cleanContents(). This ensures a standard
formatting: one command per line, single spaces between operators.
This allows for drastic simplification of this code.
"""
out_lines = [] # will return this
in_text = False # indicate if within BT/ET object
suppress = False # indicate text suppression active
make_return = False
for line in cont_lines:
if line == b"BT": # start of text object
in_text = True # switch on
out_lines.append(line) # output it
continue
if line == b"ET": # end of text object
in_text = False # switch off
out_lines.append(line) # output it
continue
if line == b"3 Tr": # text suppression operator
suppress = True # switch on
make_return = True
continue
if line[-2:] == b"Tr" and line[0] != b"3":
suppress = False # text rendering changed
out_lines.append(line)
continue
if line == b"Q": # unstack command also switches off
suppress = False
out_lines.append(line)
continue
if suppress and in_text: # suppress hidden lines
continue
out_lines.append(line)
if make_return:
return out_lines
else:
return None
if not doc.is_pdf: # only works for PDF
raise ValueError("is no PDF")
if doc.is_encrypted or doc.is_closed:
raise ValueError("closed or encrypted doc")
if clean_pages is False:
hidden_text = False
redactions = False
if metadata:
doc.set_metadata({}) # remove standard metadata
for page in doc:
if reset_fields:
# reset form fields (widgets)
for widget in page.widgets():
widget.reset()
if remove_links:
links = page.get_links() # list of all links on page
for link in links: # remove all links
page.delete_link(link)
found_redacts = False
for annot in page.annots():
if annot.type[0] == mupdf.PDF_ANNOT_FILE_ATTACHMENT and attached_files:
annot.update_file(buffer=b" ") # set file content to empty
if reset_responses:
annot.delete_responses()
if annot.type[0] == pymupdf.PDF_ANNOT_REDACT: # pylint: disable=no-member
found_redacts = True
if redactions and found_redacts:
page.apply_redactions(images=redact_images)
if not (clean_pages or hidden_text):
continue # done with the page
page.clean_contents()
if not page.get_contents():
continue
if hidden_text:
xref = page.get_contents()[0] # only one b/o cleaning!
cont = doc.xref_stream(xref)
cont_lines = remove_hidden(cont.splitlines()) # remove hidden text
if cont_lines: # something was actually removed
cont = b"\n".join(cont_lines)
doc.update_stream(xref, cont) # rewrite the page /Contents
if thumbnails: # remove page thumbnails?
if doc.xref_get_key(page.xref, "Thumb")[0] != "null":
doc.xref_set_key(page.xref, "Thumb", "null")
# pages are scrubbed, now perform document-wide scrubbing
# remove embedded files
if embedded_files:
for name in doc.embfile_names():
doc.embfile_del(name)
if xml_metadata:
doc.del_xml_metadata()
if not (xml_metadata or javascript):
xref_limit = 0
else:
xref_limit = doc.xref_length()
for xref in range(1, xref_limit):
if not doc.xref_object(xref):
msg = "bad xref %i - clean PDF before scrubbing" % xref
raise ValueError(msg)
if javascript and doc.xref_get_key(xref, "S")[1] == "/JavaScript":
# a /JavaScript action object
obj = "<</S/JavaScript/JS()>>" # replace with a null JavaScript
doc.update_object(xref, obj) # update this object
continue # no further handling
if not xml_metadata:
continue
if doc.xref_get_key(xref, "Type")[1] == "/Metadata":
# delete any metadata object directly
doc.update_object(xref, "<<>>")
doc.update_stream(xref, b"deleted", new=True)
continue
if doc.xref_get_key(xref, "Metadata")[0] != "null":
doc.xref_set_key(xref, "Metadata", "null")
def _show_fz_text( text):
#if mupdf_cppyy:
# assert isinstance( text, cppyy.gbl.mupdf.Text)
#else:
# assert isinstance( text, mupdf.Text)
num_spans = 0
num_chars = 0
span = text.m_internal.head
while 1:
if not span:
break
num_spans += 1
num_chars += span.len
span = span.next
return f'num_spans={num_spans} num_chars={num_chars}'
def fill_textbox(
writer: pymupdf.TextWriter,
rect: rect_like,
text: typing.Union[str, list],
pos: point_like = None,
font: typing.Optional[pymupdf.Font] = None,
fontsize: float = 11,
lineheight: OptFloat = None,
align: int = 0,
warn: bool = None,
right_to_left: bool = False,
small_caps: bool = False,
) -> tuple:
"""Fill a rectangle with text.
Args:
writer: pymupdf.TextWriter object (= "self")
rect: rect-like to receive the text.
text: string or list/tuple of strings.
pos: point-like start position of first word.
font: pymupdf.Font object (default pymupdf.Font('helv')).
fontsize: the fontsize.
lineheight: overwrite the font property
align: (int) 0 = left, 1 = center, 2 = right, 3 = justify
warn: (bool) text overflow action: none, warn, or exception
right_to_left: (bool) indicate right-to-left language.
"""
rect = pymupdf.Rect(rect)
if rect.is_empty:
raise ValueError("fill rect must not empty.")
if type(font) is not pymupdf.Font:
font = pymupdf.Font("helv")
def textlen(x):
"""Return length of a string."""
return font.text_length(
x, fontsize=fontsize, small_caps=small_caps
) # abbreviation
def char_lengths(x):
"""Return list of single character lengths for a string."""
return font.char_lengths(x, fontsize=fontsize, small_caps=small_caps)
def append_this(pos, text):
ret = writer.append(
pos, text, font=font, fontsize=fontsize, small_caps=small_caps
)
return ret
tolerance = fontsize * 0.2 # extra distance to left border
space_len = textlen(" ")
std_width = rect.width - tolerance
std_start = rect.x0 + tolerance
def norm_words(width, words):
"""Cut any word in pieces no longer than 'width'."""
nwords = []
word_lengths = []
for w in words:
wl_lst = char_lengths(w)
wl = sum(wl_lst)
if wl <= width: # nothing to do - copy over
nwords.append(w)
word_lengths.append(wl)
continue
# word longer than rect width - split it in parts
n = len(wl_lst)
while n > 0:
wl = sum(wl_lst[:n])
if wl <= width:
nwords.append(w[:n])
word_lengths.append(wl)
w = w[n:]
wl_lst = wl_lst[n:]
n = len(wl_lst)
else:
n -= 1
return nwords, word_lengths
def output_justify(start, line):
"""Justified output of a line."""
# ignore leading / trailing / multiple spaces
words = [w for w in line.split(" ") if w != ""]
nwords = len(words)
if nwords == 0:
return
if nwords == 1: # single word cannot be justified
append_this(start, words[0])
return
tl = sum([textlen(w) for w in words]) # total word lengths
gaps = nwords - 1 # number of word gaps
gapl = (std_width - tl) / gaps # width of each gap
for w in words:
_, lp = append_this(start, w) # output one word
start.x = lp.x + gapl # next start at word end plus gap
return
asc = font.ascender
dsc = font.descender
if not lineheight:
if asc - dsc <= 1:
lheight = 1.2
else:
lheight = asc - dsc
else:
lheight = lineheight
LINEHEIGHT = fontsize * lheight # effective line height
width = std_width # available horizontal space
# starting point of text
if pos is not None:
pos = pymupdf.Point(pos)
else: # default is just below rect top-left
pos = rect.tl + (tolerance, fontsize * asc)
if pos not in rect:
raise ValueError("Text must start in rectangle.")
# calculate displacement factor for alignment
if align == pymupdf.TEXT_ALIGN_CENTER:
factor = 0.5
elif align == pymupdf.TEXT_ALIGN_RIGHT:
factor = 1.0
else:
factor = 0
# split in lines if just a string was given
if type(text) is str:
textlines = text.splitlines()
else:
textlines = []
for line in text:
textlines.extend(line.splitlines())
max_lines = int((rect.y1 - pos.y) / LINEHEIGHT) + 1
new_lines = [] # the final list of textbox lines
no_justify = [] # no justify for these line numbers
for i, line in enumerate(textlines):
if line in ("", " "):
new_lines.append((line, space_len))
width = rect.width - tolerance
no_justify.append((len(new_lines) - 1))
continue
if i == 0:
width = rect.x1 - pos.x
else:
width = rect.width - tolerance
if right_to_left: # reverses Arabic / Hebrew text front to back
line = writer.clean_rtl(line)
tl = textlen(line)
if tl <= width: # line short enough
new_lines.append((line, tl))
no_justify.append((len(new_lines) - 1))
continue
# we need to split the line in fitting parts
words = line.split(" ") # the words in the line
# cut in parts any words that are longer than rect width
words, word_lengths = norm_words(std_width, words)
n = len(words)
while True:
line0 = " ".join(words[:n])
wl = sum(word_lengths[:n]) + space_len * (len(word_lengths[:n]) - 1)
if wl <= width:
new_lines.append((line0, wl))
words = words[n:]
word_lengths = word_lengths[n:]
n = len(words)
line0 = None
else:
n -= 1
if len(words) == 0:
break
# -------------------------------------------------------------------------
# List of lines created. Each item is (text, tl), where 'tl' is the PDF
# output length (float) and 'text' is the text. Except for justified text,
# this is output-ready.
# -------------------------------------------------------------------------
nlines = len(new_lines)
if nlines > max_lines:
msg = "Only fitting %i of %i lines." % (max_lines, nlines)
if warn is True:
pymupdf.message("Warning: " + msg)
elif warn is False:
raise ValueError(msg)
start = pymupdf.Point()
no_justify += [len(new_lines) - 1] # no justifying of last line
for i in range(max_lines):
try:
line, tl = new_lines.pop(0)
except IndexError:
if g_exceptions_verbose >= 2: pymupdf.exception_info()
break
if right_to_left: # Arabic, Hebrew
line = "".join(reversed(line))
if i == 0: # may have different start for first line
start = pos
if align == pymupdf.TEXT_ALIGN_JUSTIFY and i not in no_justify and tl < std_width:
output_justify(start, line)
start.x = std_start
start.y += LINEHEIGHT
continue
if i > 0 or pos.x == std_start: # left, center, right alignments
start.x += (width - tl) * factor
append_this(start, line)
start.x = std_start
start.y += LINEHEIGHT
return new_lines # return non-written lines
# ------------------------------------------------------------------------
# Optional Content functions
# ------------------------------------------------------------------------
def get_oc(doc: pymupdf.Document, xref: int) -> int:
"""Return optional content object xref for an image or form xobject.
Args:
xref: (int) xref number of an image or form xobject.
"""
if doc.is_closed or doc.is_encrypted:
raise ValueError("document close or encrypted")
t, name = doc.xref_get_key(xref, "Subtype")
if t != "name" or name not in ("/Image", "/Form"):
raise ValueError("bad object type at xref %i" % xref)
t, oc = doc.xref_get_key(xref, "OC")
if t != "xref":
return 0
rc = int(oc.replace("0 R", ""))
return rc
def set_oc(doc: pymupdf.Document, xref: int, oc: int) -> None:
"""Attach optional content object to image or form xobject.
Args:
xref: (int) xref number of an image or form xobject
oc: (int) xref number of an OCG or OCMD
"""
if doc.is_closed or doc.is_encrypted:
raise ValueError("document close or encrypted")
t, name = doc.xref_get_key(xref, "Subtype")
if t != "name" or name not in ("/Image", "/Form"):
raise ValueError("bad object type at xref %i" % xref)
if oc > 0:
t, name = doc.xref_get_key(oc, "Type")
if t != "name" or name not in ("/OCG", "/OCMD"):
raise ValueError("bad object type at xref %i" % oc)
if oc == 0 and "OC" in doc.xref_get_keys(xref):
doc.xref_set_key(xref, "OC", "null")
return None
doc.xref_set_key(xref, "OC", "%i 0 R" % oc)
return None
def set_ocmd(
doc: pymupdf.Document,
xref: int = 0,
ocgs: typing.Union[list, None] = None,
policy: OptStr = None,
ve: typing.Union[list, None] = None,
) -> int:
"""Create or update an OCMD object in a PDF document.
Args:
xref: (int) 0 for creating a new object, otherwise update existing one.
ocgs: (list) OCG xref numbers, which shall be subject to 'policy'.
policy: one of 'AllOn', 'AllOff', 'AnyOn', 'AnyOff' (any casing).
ve: (list) visibility expression. Use instead of 'ocgs' with 'policy'.
Returns:
Xref of the created or updated OCMD.
"""
all_ocgs = set(doc.get_ocgs().keys())
def ve_maker(ve):
if type(ve) not in (list, tuple) or len(ve) < 2:
raise ValueError("bad 've' format: %s" % ve)
if ve[0].lower() not in ("and", "or", "not"):
raise ValueError("bad operand: %s" % ve[0])
if ve[0].lower() == "not" and len(ve) != 2:
raise ValueError("bad 've' format: %s" % ve)
item = "[/%s" % ve[0].title()
for x in ve[1:]:
if type(x) is int:
if x not in all_ocgs:
raise ValueError("bad OCG %i" % x)
item += " %i 0 R" % x
else:
item += " %s" % ve_maker(x)
item += "]"
return item
text = "<</Type/OCMD"
if ocgs and type(ocgs) in (list, tuple): # some OCGs are provided
s = set(ocgs).difference(all_ocgs) # contains illegal xrefs
if s != set():
msg = "bad OCGs: %s" % s
raise ValueError(msg)
text += "/OCGs[" + " ".join(map(lambda x: "%i 0 R" % x, ocgs)) + "]"
if policy:
policy = str(policy).lower()
pols = {
"anyon": "AnyOn",
"allon": "AllOn",
"anyoff": "AnyOff",
"alloff": "AllOff",
}
if policy not in ("anyon", "allon", "anyoff", "alloff"):
raise ValueError("bad policy: %s" % policy)
text += "/P/%s" % pols[policy]
if ve:
text += "/VE%s" % ve_maker(ve)
text += ">>"
# make new object or replace old OCMD (check type first)
if xref == 0:
xref = doc.get_new_xref()
elif "/Type/OCMD" not in doc.xref_object(xref, compressed=True):
raise ValueError("bad xref or not an OCMD")
doc.update_object(xref, text)
return xref
def get_ocmd(doc: pymupdf.Document, xref: int) -> dict:
"""Return the definition of an OCMD (optional content membership dictionary).
Recognizes PDF dict keys /OCGs (PDF array of OCGs), /P (policy string) and
/VE (visibility expression, PDF array). Via string manipulation, this
info is converted to a Python dictionary with keys "xref", "ocgs", "policy"
and "ve" - ready to recycle as input for 'set_ocmd()'.
"""
if xref not in range(doc.xref_length()):
raise ValueError("bad xref")
text = doc.xref_object(xref, compressed=True)
if "/Type/OCMD" not in text:
raise ValueError("bad object type")
textlen = len(text)
p0 = text.find("/OCGs[") # look for /OCGs key
p1 = text.find("]", p0)
if p0 < 0 or p1 < 0: # no OCGs found
ocgs = None
else:
ocgs = text[p0 + 6 : p1].replace("0 R", " ").split()
ocgs = list(map(int, ocgs))
p0 = text.find("/P/") # look for /P policy key
if p0 < 0:
policy = None
else:
p1 = text.find("ff", p0)
if p1 < 0:
p1 = text.find("on", p0)
if p1 < 0: # some irregular syntax
raise ValueError("bad object at xref")
else:
policy = text[p0 + 3 : p1 + 2]
p0 = text.find("/VE[") # look for /VE visibility expression key
if p0 < 0: # no visibility expression found
ve = None
else:
lp = rp = 0 # find end of /VE by finding last ']'.
p1 = p0
while lp < 1 or lp != rp:
p1 += 1
if not p1 < textlen: # some irregular syntax
raise ValueError("bad object at xref")
if text[p1] == "[":
lp += 1
if text[p1] == "]":
rp += 1
# p1 now positioned at the last "]"
ve = text[p0 + 3 : p1 + 1] # the PDF /VE array
ve = (
ve.replace("/And", '"and",')
.replace("/Not", '"not",')
.replace("/Or", '"or",')
)
ve = ve.replace(" 0 R]", "]").replace(" 0 R", ",").replace("][", "],[")
import json
try:
ve = json.loads(ve)
except Exception:
pymupdf.exception_info()
pymupdf.message(f"bad /VE key: {ve!r}")
raise
return {"xref": xref, "ocgs": ocgs, "policy": policy, "ve": ve}
"""
Handle page labels for PDF documents.
Reading
-------
* compute the label of a page
* find page number(s) having the given label.
Writing
-------
Supports setting (defining) page labels for PDF documents.
A big Thank You goes to WILLIAM CHAPMAN who contributed the idea and
significant parts of the following code during late December 2020
through early January 2021.
"""
def rule_dict(item):
"""Make a Python dict from a PDF page label rule.
Args:
item -- a tuple (pno, rule) with the start page number and the rule
string like <</S/D...>>.
Returns:
A dict like
{'startpage': int, 'prefix': str, 'style': str, 'firstpagenum': int}.
"""
# Jorj McKie, 2021-01-06
pno, rule = item
rule = rule[2:-2].split("/")[1:] # strip "<<" and ">>"
d = {"startpage": pno, "prefix": "", "firstpagenum": 1}
skip = False
for i, item in enumerate(rule): # pylint: disable=redefined-argument-from-local
if skip: # this item has already been processed
skip = False # deactivate skipping again
continue
if item == "S": # style specification
d["style"] = rule[i + 1] # next item has the style
skip = True # do not process next item again
continue
if item.startswith("P"): # prefix specification: extract the string
x = item[1:].replace("(", "").replace(")", "")
d["prefix"] = x
continue
if item.startswith("St"): # start page number specification
x = int(item[2:])
d["firstpagenum"] = x
return d
def get_label_pno(pgNo, labels):
"""Return the label for this page number.
Args:
pgNo: page number, 0-based.
labels: result of doc._get_page_labels().
Returns:
The label (str) of the page number. Errors return an empty string.
"""
# Jorj McKie, 2021-01-06
item = [x for x in labels if x[0] <= pgNo][-1]
rule = rule_dict(item)
prefix = rule.get("prefix", "")
style = rule.get("style", "")
# make sure we start at 0 when enumerating the alphabet
delta = -1 if style in ("a", "A") else 0
pagenumber = pgNo - rule["startpage"] + rule["firstpagenum"] + delta
return construct_label(style, prefix, pagenumber)
def get_label(page):
"""Return the label for this PDF page.
Args:
page: page object.
Returns:
The label (str) of the page. Errors return an empty string.
"""
# Jorj McKie, 2021-01-06
labels = page.parent._get_page_labels()
if not labels:
return ""
labels.sort()
return get_label_pno(page.number, labels)
def get_page_numbers(doc, label, only_one=False):
"""Return a list of page numbers with the given label.
Args:
doc: PDF document object (resp. 'self').
label: (str) label.
only_one: (bool) stop searching after first hit.
Returns:
List of page numbers having this label.
"""
# Jorj McKie, 2021-01-06
numbers = []
if not label:
return numbers
labels = doc._get_page_labels()
if labels == []:
return numbers
for i in range(doc.page_count):
plabel = get_label_pno(i, labels)
if plabel == label:
numbers.append(i)
if only_one:
break
return numbers
def construct_label(style, prefix, pno) -> str:
"""Construct a label based on style, prefix and page number."""
# William Chapman, 2021-01-06
n_str = ""
if style == "D":
n_str = str(pno)
elif style == "r":
n_str = integerToRoman(pno).lower()
elif style == "R":
n_str = integerToRoman(pno).upper()
elif style == "a":
n_str = integerToLetter(pno).lower()
elif style == "A":
n_str = integerToLetter(pno).upper()
result = prefix + n_str
return result
def integerToLetter(i) -> str:
"""Returns letter sequence string for integer i."""
# William Chapman, Jorj McKie, 2021-01-06
import string
ls = string.ascii_uppercase
n, a = 1, i
while pow(26, n) <= a:
a -= int(math.pow(26, n))
n += 1
str_t = ""
for j in reversed(range(n)):
f, g = divmod(a, int(math.pow(26, j)))
str_t += ls[f]
a = g
return str_t
def integerToRoman(num: int) -> str:
"""Return roman numeral for an integer."""
# William Chapman, Jorj McKie, 2021-01-06
roman = (
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
)
def roman_num(num):
for r, ltr in roman:
x, _ = divmod(num, r)
yield ltr * x
num -= r * x
if num <= 0:
break
return "".join([a for a in roman_num(num)])
def get_page_labels(doc):
"""Return page label definitions in PDF document.
Args:
doc: PDF document (resp. 'self').
Returns:
A list of dictionaries with the following format:
{'startpage': int, 'prefix': str, 'style': str, 'firstpagenum': int}.
"""
# Jorj McKie, 2021-01-10
return [rule_dict(item) for item in doc._get_page_labels()]
def set_page_labels(doc, labels):
"""Add / replace page label definitions in PDF document.
Args:
doc: PDF document (resp. 'self').
labels: list of label dictionaries like:
{'startpage': int, 'prefix': str, 'style': str, 'firstpagenum': int},
as returned by get_page_labels().
"""
# William Chapman, 2021-01-06
def create_label_str(label):
"""Convert Python label dict to corresponding PDF rule string.
Args:
label: (dict) build rule for the label.
Returns:
PDF label rule string wrapped in "<<", ">>".
"""
s = "%i<<" % label["startpage"]
if label.get("prefix", "") != "":
s += "/P(%s)" % label["prefix"]
if label.get("style", "") != "":
s += "/S/%s" % label["style"]
if label.get("firstpagenum", 1) > 1:
s += "/St %i" % label["firstpagenum"]
s += ">>"
return s
def create_nums(labels):
"""Return concatenated string of all labels rules.
Args:
labels: (list) dictionaries as created by function 'rule_dict'.
Returns:
PDF compatible string for page label definitions, ready to be
enclosed in PDF array 'Nums[...]'.
"""
labels.sort(key=lambda x: x["startpage"])
s = "".join([create_label_str(label) for label in labels])
return s
doc._set_page_labels(create_nums(labels))
# End of Page Label Code -------------------------------------------------
def has_links(doc: pymupdf.Document) -> bool:
"""Check whether there are links on any page."""
if doc.is_closed:
raise ValueError("document closed")
if not doc.is_pdf:
raise ValueError("is no PDF")
for i in range(doc.page_count):
for item in doc.page_annot_xrefs(i):
if item[1] == pymupdf.PDF_ANNOT_LINK: # pylint: disable=no-member
return True
return False
def has_annots(doc: pymupdf.Document) -> bool:
"""Check whether there are annotations on any page."""
if doc.is_closed:
raise ValueError("document closed")
if not doc.is_pdf:
raise ValueError("is no PDF")
for i in range(doc.page_count):
for item in doc.page_annot_xrefs(i):
# pylint: disable=no-member
if not (item[1] == pymupdf.PDF_ANNOT_LINK or item[1] == pymupdf.PDF_ANNOT_WIDGET):
return True
return False
# -------------------------------------------------------------------
# Functions to recover the quad contained in a text extraction bbox
# -------------------------------------------------------------------
def recover_bbox_quad(line_dir: tuple, span: dict, bbox: tuple) -> pymupdf.Quad:
"""Compute the quad located inside the bbox.
The bbox may be any of the resp. tuples occurring inside the given span.
Args:
line_dir: (tuple) 'line["dir"]' of the owning line or None.
span: (dict) the span. May be from get_texttrace() method.
bbox: (tuple) the bbox of the span or any of its characters.
Returns:
The quad which is wrapped by the bbox.
"""
if line_dir is None:
line_dir = span["dir"]
cos, sin = line_dir
bbox = pymupdf.Rect(bbox) # make it a rect
if pymupdf.TOOLS.set_small_glyph_heights(): # ==> just fontsize as height
d = 1
else:
d = span["ascender"] - span["descender"]
height = d * span["size"] # the quad's rectangle height
# The following are distances from the bbox corners, at which we find the
# respective quad points. The computation depends on in which quadrant the
# text writing angle is located.
hs = height * sin
hc = height * cos
if hc >= 0 and hs <= 0: # quadrant 1
ul = bbox.bl - (0, hc)
ur = bbox.tr + (hs, 0)
ll = bbox.bl - (hs, 0)
lr = bbox.tr + (0, hc)
elif hc <= 0 and hs <= 0: # quadrant 2
ul = bbox.br + (hs, 0)
ur = bbox.tl - (0, hc)
ll = bbox.br + (0, hc)
lr = bbox.tl - (hs, 0)
elif hc <= 0 and hs >= 0: # quadrant 3
ul = bbox.tr - (0, hc)
ur = bbox.bl + (hs, 0)
ll = bbox.tr - (hs, 0)
lr = bbox.bl + (0, hc)
else: # quadrant 4
ul = bbox.tl + (hs, 0)
ur = bbox.br - (0, hc)
ll = bbox.tl + (0, hc)
lr = bbox.br - (hs, 0)
return pymupdf.Quad(ul, ur, ll, lr)
def recover_quad(line_dir: tuple, span: dict) -> pymupdf.Quad:
"""Recover the quadrilateral of a text span.
Args:
line_dir: (tuple) 'line["dir"]' of the owning line.
span: the span.
Returns:
The quadrilateral enveloping the span's text.
"""
if type(line_dir) is not tuple or len(line_dir) != 2:
raise ValueError("bad line dir argument")
if type(span) is not dict:
raise ValueError("bad span argument")
return recover_bbox_quad(line_dir, span, span["bbox"])
def recover_line_quad(line: dict, spans: list = None) -> pymupdf.Quad:
"""Calculate the line quad for 'dict' / 'rawdict' text extractions.
The lower quad points are those of the first, resp. last span quad.
The upper points are determined by the maximum span quad height.
From this, compute a rect with bottom-left in (0, 0), convert this to a
quad and rotate and shift back to cover the text of the spans.
Args:
spans: (list, optional) sub-list of spans to consider.
Returns:
pymupdf.Quad covering selected spans.
"""
if spans is None: # no sub-selection
spans = line["spans"] # all spans
if len(spans) == 0:
raise ValueError("bad span list")
line_dir = line["dir"] # text direction
cos, sin = line_dir
q0 = recover_quad(line_dir, spans[0]) # quad of first span
if len(spans) > 1: # get quad of last span
q1 = recover_quad(line_dir, spans[-1])
else:
q1 = q0 # last = first
line_ll = q0.ll # lower-left of line quad
line_lr = q1.lr # lower-right of line quad
mat0 = pymupdf.planish_line(line_ll, line_lr)
# map base line to x-axis such that line_ll goes to (0, 0)
x_lr = line_lr * mat0
small = pymupdf.TOOLS.set_small_glyph_heights() # small glyph heights?
h = max(
[s["size"] * (1 if small else (s["ascender"] - s["descender"])) for s in spans]
)
line_rect = pymupdf.Rect(0, -h, x_lr.x, 0) # line rectangle
line_quad = line_rect.quad # make it a quad and:
line_quad *= ~mat0
return line_quad
def recover_span_quad(line_dir: tuple, span: dict, chars: list = None) -> pymupdf.Quad:
"""Calculate the span quad for 'dict' / 'rawdict' text extractions.
Notes:
There are two execution paths:
1. For the full span quad, the result of 'recover_quad' is returned.
2. For the quad of a sub-list of characters, the char quads are
computed and joined. This is only supported for the "rawdict"
extraction option.
Args:
line_dir: (tuple) 'line["dir"]' of the owning line.
span: (dict) the span.
chars: (list, optional) sub-list of characters to consider.
Returns:
pymupdf.Quad covering selected characters.
"""
if line_dir is None: # must be a span from get_texttrace()
line_dir = span["dir"]
if chars is None: # no sub-selection
return recover_quad(line_dir, span)
if "chars" not in span.keys():
raise ValueError("need 'rawdict' option to sub-select chars")
q0 = recover_char_quad(line_dir, span, chars[0]) # quad of first char
if len(chars) > 1: # get quad of last char
q1 = recover_char_quad(line_dir, span, chars[-1])
else:
q1 = q0 # last = first
span_ll = q0.ll # lower-left of span quad
span_lr = q1.lr # lower-right of span quad
mat0 = pymupdf.planish_line(span_ll, span_lr)
# map base line to x-axis such that span_ll goes to (0, 0)
x_lr = span_lr * mat0
small = pymupdf.TOOLS.set_small_glyph_heights() # small glyph heights?
h = span["size"] * (1 if small else (span["ascender"] - span["descender"]))
span_rect = pymupdf.Rect(0, -h, x_lr.x, 0) # line rectangle
span_quad = span_rect.quad # make it a quad and:
span_quad *= ~mat0 # rotate back and shift back
return span_quad
def recover_char_quad(line_dir: tuple, span: dict, char: dict) -> pymupdf.Quad:
"""Recover the quadrilateral of a text character.
This requires the "rawdict" option of text extraction.
Args:
line_dir: (tuple) 'line["dir"]' of the span's line.
span: (dict) the span dict.
char: (dict) the character dict.
Returns:
The quadrilateral enveloping the character.
"""
if line_dir is None:
line_dir = span["dir"]
if type(line_dir) is not tuple or len(line_dir) != 2:
raise ValueError("bad line dir argument")
if type(span) is not dict:
raise ValueError("bad span argument")
if type(char) is dict:
bbox = pymupdf.Rect(char["bbox"])
elif type(char) is tuple:
bbox = pymupdf.Rect(char[3])
else:
raise ValueError("bad span argument")
return recover_bbox_quad(line_dir, span, bbox)
# -------------------------------------------------------------------
# Building font subsets using fontTools
# -------------------------------------------------------------------
def subset_fonts(doc: pymupdf.Document, verbose: bool = False, fallback: bool = False) -> None:
"""Build font subsets of a PDF. Requires package 'fontTools'.
Eligible fonts are potentially replaced by smaller versions. Page text is
NOT rewritten and thus should retain properties like being hidden or
controlled by optional content.
This method by default uses MuPDF's own internal feature to create subset
fonts. As this is a new function, errors may still occur. In this case,
please fall back to using the previous version by using "fallback=True".
"""
# Font binaries: - "buffer" -> (names, xrefs, (unicodes, glyphs))
# An embedded font is uniquely defined by its fontbuffer only. It may have
# multiple names and xrefs.
# Once the sets of used unicodes and glyphs are known, we compute a
# smaller version of the buffer user package fontTools.
if fallback is False: # by default use MuPDF function
pdf = mupdf.pdf_document_from_fz_document(doc)
mupdf.pdf_subset_fonts2(pdf, list(range(doc.page_count)))
return
font_buffers = {}
def get_old_widths(xref):
"""Retrieve old font '/W' and '/DW' values."""
df = doc.xref_get_key(xref, "DescendantFonts")
if df[0] != "array": # only handle xref specifications
return None, None
df_xref = int(df[1][1:-1].replace("0 R", ""))
widths = doc.xref_get_key(df_xref, "W")
if widths[0] != "array": # no widths key found
widths = None
else:
widths = widths[1]
dwidths = doc.xref_get_key(df_xref, "DW")
if dwidths[0] != "int":
dwidths = None
else:
dwidths = dwidths[1]
return widths, dwidths
def set_old_widths(xref, widths, dwidths):
"""Restore the old '/W' and '/DW' in subsetted font.
If either parameter is None or evaluates to False, the corresponding
dictionary key will be set to null.
"""
df = doc.xref_get_key(xref, "DescendantFonts")
if df[0] != "array": # only handle xref specs
return None
df_xref = int(df[1][1:-1].replace("0 R", ""))
if (type(widths) is not str or not widths) and doc.xref_get_key(df_xref, "W")[
0
] != "null":
doc.xref_set_key(df_xref, "W", "null")
else:
doc.xref_set_key(df_xref, "W", widths)
if (type(dwidths) is not str or not dwidths) and doc.xref_get_key(
df_xref, "DW"
)[0] != "null":
doc.xref_set_key(df_xref, "DW", "null")
else:
doc.xref_set_key(df_xref, "DW", dwidths)
return None
def set_subset_fontname(new_xref):
"""Generate a name prefix to tag a font as subset.
We use a random generator to select 6 upper case ASCII characters.
The prefixed name must be put in the font xref as the "/BaseFont" value
and in the FontDescriptor object as the '/FontName' value.
"""
# The following generates a prefix like 'ABCDEF+'
import random
import string
prefix = "".join(random.choices(tuple(string.ascii_uppercase), k=6)) + "+"
font_str = doc.xref_object(new_xref, compressed=True)
font_str = font_str.replace("/BaseFont/", "/BaseFont/" + prefix)
df = doc.xref_get_key(new_xref, "DescendantFonts")
if df[0] == "array":
df_xref = int(df[1][1:-1].replace("0 R", ""))
fd = doc.xref_get_key(df_xref, "FontDescriptor")
if fd[0] == "xref":
fd_xref = int(fd[1].replace("0 R", ""))
fd_str = doc.xref_object(fd_xref, compressed=True)
fd_str = fd_str.replace("/FontName/", "/FontName/" + prefix)
doc.update_object(fd_xref, fd_str)
doc.update_object(new_xref, font_str)
def build_subset(buffer, unc_set, gid_set):
"""Build font subset using fontTools.
Args:
buffer: (bytes) the font given as a binary buffer.
unc_set: (set) required glyph ids.
Returns:
Either None if subsetting is unsuccessful or the subset font buffer.
"""
try:
import fontTools.subset as fts
except ImportError:
if g_exceptions_verbose: pymupdf.exception_info()
pymupdf.message("This method requires fontTools to be installed.")
raise
import tempfile
with tempfile.TemporaryDirectory() as tmp_dir:
oldfont_path = f"{tmp_dir}/oldfont.ttf"
newfont_path = f"{tmp_dir}/newfont.ttf"
uncfile_path = f"{tmp_dir}/uncfile.txt"
args = [
oldfont_path,
"--retain-gids",
f"--output-file={newfont_path}",
"--layout-features='*'",
"--passthrough-tables",
"--ignore-missing-glyphs",
"--ignore-missing-unicodes",
"--symbol-cmap",
]
# store glyph ids or unicodes as file
with open(f"{tmp_dir}/uncfile.txt", "w", encoding='utf8') as unc_file:
if 0xFFFD in unc_set: # error unicode exists -> use glyphs
args.append(f"--gids-file={uncfile_path}")
gid_set.add(189)
unc_list = list(gid_set)
for unc in unc_list:
unc_file.write("%i\n" % unc)
else:
args.append(f"--unicodes-file={uncfile_path}")
unc_set.add(255)
unc_list = list(unc_set)
for unc in unc_list:
unc_file.write("%04x\n" % unc)
# store fontbuffer as a file
with open(oldfont_path, "wb") as fontfile:
fontfile.write(buffer)
try:
os.remove(newfont_path) # remove old file
except Exception:
pass
try: # invoke fontTools subsetter
fts.main(args)
font = pymupdf.Font(fontfile=newfont_path)
new_buffer = font.buffer # subset font binary
if font.glyph_count == 0: # intercept empty font
new_buffer = None
except Exception:
pymupdf.exception_info()
new_buffer = None
return new_buffer
def repl_fontnames(doc):
"""Populate 'font_buffers'.
For each font candidate, store its xref and the list of names
by which PDF text may refer to it (there may be multiple).
"""
def norm_name(name):
"""Recreate font name that contains PDF hex codes.
E.g. #20 -> space, chr(32)
"""
while "#" in name:
p = name.find("#")
c = int(name[p + 1 : p + 3], 16)
name = name.replace(name[p : p + 3], chr(c))
return name
def get_fontnames(doc, item):
"""Return a list of fontnames for an item of page.get_fonts().
There may be multiple names e.g. for Type0 fonts.
"""
fontname = item[3]
names = [fontname]
fontname = doc.xref_get_key(item[0], "BaseFont")[1][1:]
fontname = norm_name(fontname)
if fontname not in names:
names.append(fontname)
descendents = doc.xref_get_key(item[0], "DescendantFonts")
if descendents[0] != "array":
return names
descendents = descendents[1][1:-1]
if descendents.endswith(" 0 R"):
xref = int(descendents[:-4])
descendents = doc.xref_object(xref, compressed=True)
p1 = descendents.find("/BaseFont")
if p1 >= 0:
p2 = descendents.find("/", p1 + 1)
p1 = min(descendents.find("/", p2 + 1), descendents.find(">>", p2 + 1))
fontname = descendents[p2 + 1 : p1]
fontname = norm_name(fontname)
if fontname not in names:
names.append(fontname)
return names
for i in range(doc.page_count):
for f in doc.get_page_fonts(i, full=True):
font_xref = f[0] # font xref
font_ext = f[1] # font file extension
basename = f[3] # font basename
if font_ext not in ( # skip if not supported by fontTools
"otf",
"ttf",
"woff",
"woff2",
):
continue
# skip fonts which already are subsets
if len(basename) > 6 and basename[6] == "+":
continue
extr = doc.extract_font(font_xref)
fontbuffer = extr[-1]
names = get_fontnames(doc, f)
name_set, xref_set, subsets = font_buffers.get(
fontbuffer, (set(), set(), (set(), set()))
)
xref_set.add(font_xref)
for name in names:
name_set.add(name)
font = pymupdf.Font(fontbuffer=fontbuffer)
name_set.add(font.name)
del font
font_buffers[fontbuffer] = (name_set, xref_set, subsets)
def find_buffer_by_name(name):
for buffer, (name_set, _, _) in font_buffers.items():
if name in name_set:
return buffer
return None
# -----------------
# main function
# -----------------
repl_fontnames(doc) # populate font information
if not font_buffers: # nothing found to do
if verbose:
pymupdf.message(f'No fonts to subset.')
return 0
old_fontsize = 0
new_fontsize = 0
for fontbuffer in font_buffers.keys():
old_fontsize += len(fontbuffer)
# Scan page text for usage of subsettable fonts
for page in doc:
# go through the text and extend set of used glyphs by font
# we use a modified MuPDF trace device, which delivers us glyph ids.
for span in page.get_texttrace():
if type(span) is not dict: # skip useless information
continue
fontname = span["font"][:33] # fontname for the span
buffer = find_buffer_by_name(fontname)
if buffer is None:
continue
name_set, xref_set, (set_ucs, set_gid) = font_buffers[buffer]
for c in span["chars"]:
set_ucs.add(c[0]) # unicode
set_gid.add(c[1]) # glyph id
font_buffers[buffer] = (name_set, xref_set, (set_ucs, set_gid))
# build the font subsets
for old_buffer, (name_set, xref_set, subsets) in font_buffers.items():
new_buffer = build_subset(old_buffer, subsets[0], subsets[1])
fontname = list(name_set)[0]
if new_buffer is None or len(new_buffer) >= len(old_buffer):
# subset was not created or did not get smaller
if verbose:
pymupdf.message(f'Cannot subset {fontname!r}.')
continue
if verbose:
pymupdf.message(f"Built subset of font {fontname!r}.")
val = doc._insert_font(fontbuffer=new_buffer) # store subset font in PDF
new_xref = val[0] # get its xref
set_subset_fontname(new_xref) # tag fontname as subset font
font_str = doc.xref_object( # get its object definition
new_xref,
compressed=True,
)
# walk through the original font xrefs and replace each by the subset def
for font_xref in xref_set:
# we need the original '/W' and '/DW' width values
width_table, def_width = get_old_widths(font_xref)
# ... and replace original font definition at xref with it
doc.update_object(font_xref, font_str)
# now copy over old '/W' and '/DW' values
if width_table or def_width:
set_old_widths(font_xref, width_table, def_width)
# 'new_xref' remains unused in the PDF and must be removed
# by garbage collection.
new_fontsize += len(new_buffer)
return old_fontsize - new_fontsize
# -------------------------------------------------------------------
# Copy XREF object to another XREF
# -------------------------------------------------------------------
def xref_copy(doc: pymupdf.Document, source: int, target: int, *, keep: list = None) -> None:
"""Copy a PDF dictionary object to another one given their xref numbers.
Args:
doc: PDF document object
source: source xref number
target: target xref number, the xref must already exist
keep: an optional list of 1st level keys in target that should not be
removed before copying.
Notes:
This works similar to the copy() method of dictionaries in Python. The
source may be a stream object.
"""
if doc.xref_is_stream(source):
# read new xref stream, maintaining compression
stream = doc.xref_stream_raw(source)
doc.update_stream(
target,
stream,
compress=False, # keeps source compression
new=True, # in case target is no stream
)
# empty the target completely, observe exceptions
if keep is None:
keep = []
for key in doc.xref_get_keys(target):
if key in keep:
continue
doc.xref_set_key(target, key, "null")
# copy over all source dict items
for key in doc.xref_get_keys(source):
item = doc.xref_get_key(source, key)
doc.xref_set_key(target, key, item[1])
| 200,105 | Python | .py | 5,226 | 29.342518 | 203 | 0.547429 | pymupdf/PyMuPDF | 5,009 | 480 | 32 | AGPL-3.0 | 9/5/2024, 5:12:54 PM (Europe/Amsterdam) |
21,298 | __init__.py | pymupdf_PyMuPDF/src/__init__.py | '''
PyMuPDF implemented on top of MuPDF Python bindings.
License:
SPDX-License-Identifier: GPL-3.0-only
'''
# To reduce startup times, we don't import everything we require here.
#
import atexit
import binascii
import collections
import inspect
import io
import math
import os
import pathlib
import glob
import re
import string
import sys
import tarfile
import time
import typing
import warnings
import weakref
import zipfile
from . import extra
# Set up g_out_log and g_out_message from environment variables.
#
# PYMUPDF_MESSAGE controls the destination of user messages (from function
# `pymupdf.message()`).
#
# PYMUPDF_LOG controls the destination of internal development logging (from
# function `pymupdf.log()`).
#
# For syntax, see _make_output()'s `text` arg.
#
def _make_output(
*,
text=None,
fd=None,
stream=None,
path=None,
path_append=None,
pylogging=None,
pylogging_logger=None,
pylogging_level=None,
pylogging_name=None,
default=None,
):
'''
Returns a stream that writes to a specified destination, which can be a
file descriptor, a file, an existing stream or Python's `logging' system.
Args:
text: text specification of destination.
fd:<int> - write to file descriptor.
path:<str> - write to file.
path+:<str> - append to file.
logging:<items> - write to Python `logging` module.
items: comma-separated <name=value> pairs.
level=<int>
name=<str>.
Other names are ignored.
fd: an int file descriptor.
stream: something with methods .write(text) and .flush().
If specified we simply return <stream>.
path: a file path.
If specified we return a stream that writes to this file.
path_append: a file path.
If specified we return a stream that appends to this file.
pylogging*:
if any of these args is not None, we return a stream that writes to
Python's `logging` module.
pylogging:
Unused other than to activate use of logging module.
pylogging_logger:
A logging.Logger; If None, set from <pylogging_name>.
pylogging_level:
An int log level, if None we use
pylogging_logger.getEffectiveLevel().
pylogging_name:
Only used if <pylogging_logger> is None:
If <pylogging_name> is None, we set it to 'pymupdf'.
Then we do: pylogging_logger = logging.getLogger(pylogging_name)
'''
if text is not None:
# Textual specification, for example from from environment variable.
if text.startswith('fd:'):
fd = int(text[3:])
elif text.startswith('path:'):
path = text[5:]
elif text.startswith('path+'):
path_append = text[5:]
elif text.startswith('logging:'):
pylogging = True
items_d = dict()
items = text[8:].split(',')
#items_d = {n: v for (n, v) in [item.split('=', 1) for item in items]}
for item in items:
if not item:
continue
nv = item.split('=', 1)
assert len(nv) == 2, f'Need `=` in {item=}.'
n, v = nv
items_d[n] = v
pylogging_level = items_d.get('level')
if pylogging_level is not None:
pylogging_level = int(pylogging_level)
pylogging_name = items_d.get('name', 'pymupdf')
else:
assert 0, f'Unrecognised {text=}.'
if fd is not None:
ret = open(fd, mode='w', closefd=False)
elif stream is not None:
assert hasattr(stream, 'write')
assert hasattr(stream, 'flush')
ret = stream
elif path is not None:
ret = open(path, 'w')
elif path_append is not None:
ret = open(path_append, 'a')
elif (0
or pylogging is not None
or pylogging_logger is not None
or pylogging_level is not None
or pylogging_name is not None
):
import logging
if pylogging_logger is None:
if pylogging_name is None:
pylogging_name = 'pymupdf'
pylogging_logger = logging.getLogger(pylogging_name)
assert isinstance(pylogging_logger, logging.Logger)
if pylogging_level is None:
pylogging_level = pylogging_logger.getEffectiveLevel()
class Out:
def write(self, text):
# `logging` module appends newlines, but so does the `print()`
# functions in our caller message() and log() fns, so we need to
# remove them here.
text = text.rstrip('\n')
if text:
pylogging_logger.log(pylogging_level, text)
def flush(self):
pass
ret = Out()
elif default:
ret = default
else:
assert 0, f'No output specified.'
return ret
# Set steam used by PyMuPDF messaging.
_g_out_message = _make_output(text=os.environ.get('PYMUPDF_MESSAGE'), default=sys.stdout)
# Set steam used by PyMuPDF development/debugging logging.
_g_out_log = _make_output(text=os.environ.get('PYMUPDF_LOG'), default=sys.stdout)
# Things for testing logging.
_g_log_items = list()
_g_log_items_active = False
def _log_items():
return _g_log_items
def _log_items_active(active):
global _g_log_items_active
_g_log_items_active = active
def _log_items_clear():
del _g_log_items[:]
def set_messages(
*,
text=None,
fd=None,
stream=None,
path=None,
path_append=None,
pylogging=None,
pylogging_logger=None,
pylogging_level=None,
pylogging_name=None,
):
'''
Sets destination of PyMuPDF messages. See _make_output() for details.
'''
global _g_out_message
_g_out_message = _make_output(
text=text,
fd=fd,
stream=stream,
path=path,
path_append=path_append,
pylogging=pylogging,
pylogging_logger=pylogging_logger,
pylogging_level=pylogging_level,
pylogging_name=pylogging_name,
default=_g_out_message,
)
def set_log(
*,
text=None,
fd=None,
stream=None,
path=None,
path_append=None,
pylogging=None,
pylogging_logger=None,
pylogging_level=None,
pylogging_name=None,
):
'''
Sets destination of PyMuPDF development/debugging logging. See
_make_output() for details.
'''
global _g_out_log
_g_out_log = _make_output(
text=text,
fd=fd,
stream=stream,
path=path,
path_append=path_append,
pylogging=pylogging,
pylogging_logger=pylogging_logger,
pylogging_level=pylogging_level,
pylogging_name=pylogging_name,
default=_g_out_log,
)
def log( text='', caller=1):
'''
For development/debugging diagnostics.
'''
try:
stack = inspect.stack(context=0)
except StopIteration:
pass
else:
frame_record = stack[caller]
try:
filename = os.path.relpath(frame_record.filename)
except Exception: # Can fail on windows.
filename = frame_record.filename
line = frame_record.lineno
function = frame_record.function
text = f'{filename}:{line}:{function}(): {text}'
if _g_log_items_active:
_g_log_items.append(text)
print(text, file=_g_out_log, flush=1)
def message(text=''):
'''
For user messages.
'''
print(text, file=_g_out_message, flush=1)
def exception_info():
import traceback
log(f'exception_info:')
log(traceback.format_exc())
# PDF names must not contain these characters:
INVALID_NAME_CHARS = set(string.whitespace + "()<>[]{}/%" + chr(0))
def get_env_bool( name, default):
'''
Returns `True`, `False` or `default` depending on whether $<name> is '1',
'0' or unset. Otherwise assert-fails.
'''
v = os.environ.get( name)
if v is None:
ret = default
elif v == '1':
ret = True
elif v == '0':
ret = False
else:
assert 0, f'Unrecognised value for {name}: {v!r}'
if ret != default:
log(f'Using non-default setting from {name}: {v!r}')
return ret
def get_env_int( name, default):
'''
Returns `True`, `False` or `default` depending on whether $<name> is '1',
'0' or unset. Otherwise assert-fails.
'''
v = os.environ.get( name)
if v is None:
ret = default
else:
ret = int(v)
if ret != default:
log(f'Using non-default setting from {name}: {v}')
return ret
# All our `except ...` blocks output diagnostics if `g_exceptions_verbose` is
# true.
g_exceptions_verbose = get_env_int( 'PYMUPDF_EXCEPTIONS_VERBOSE', 1)
# $PYMUPDF_USE_EXTRA overrides whether to use optimised C fns in `extra`.
#
g_use_extra = get_env_bool( 'PYMUPDF_USE_EXTRA', True)
# Global switches
#
class _Globals:
def __init__(self):
self.no_device_caching = 0
self.small_glyph_heights = 0
self.subset_fontnames = 0
self.skip_quad_corrections = 0
_globals = _Globals()
# Optionally use MuPDF via cppyy bindings; experimental and not tested recently
# as of 2023-01-20 11:51:40
#
mupdf_cppyy = os.environ.get( 'MUPDF_CPPYY')
if mupdf_cppyy is not None:
# pylint: disable=all
log( f'{__file__}: $MUPDF_CPPYY={mupdf_cppyy!r} so attempting to import mupdf_cppyy.')
log( f'{__file__}: $PYTHONPATH={os.environ["PYTHONPATH"]}')
if mupdf_cppyy == '':
import mupdf_cppyy
else:
import importlib
mupdf_cppyy = importlib.machinery.SourceFileLoader(
'mupdf_cppyy',
mupdf_cppyy
).load_module()
mupdf = mupdf_cppyy.cppyy.gbl.mupdf
else:
# Use MuPDF Python SWIG bindings. We allow import from either our own
# directory for conventional wheel installs, or from separate place in case
# we are using a separately-installed system installation of mupdf.
#
try:
from . import mupdf
except Exception:
import mupdf
mupdf.reinit_singlethreaded()
def _int_rc(text):
'''
Converts string to int, ignoring trailing 'rc...'.
'''
rc = text.find('rc')
if rc >= 0:
text = text[:rc]
return int(text)
# Basic version information.
#
pymupdf_version = "1.24.12"
mupdf_version = mupdf.FZ_VERSION
pymupdf_date = "2024-10-21 00:00:01"
# Versions as tuples; useful when comparing versions.
#
pymupdf_version_tuple = tuple( [_int_rc(i) for i in pymupdf_version.split('.')])
mupdf_version_tuple = tuple( [_int_rc(i) for i in mupdf_version.split('.')])
assert mupdf_version_tuple == (mupdf.FZ_VERSION_MAJOR, mupdf.FZ_VERSION_MINOR, mupdf.FZ_VERSION_PATCH), \
f'Inconsistent MuPDF version numbers: {mupdf_version_tuple=} != {(mupdf.FZ_VERSION_MAJOR, mupdf.FZ_VERSION_MINOR, mupdf.FZ_VERSION_PATCH)=}'
# Legacy version information.
#
pymupdf_date2 = pymupdf_date.replace('-', '').replace(' ', '').replace(':', '')
version = (pymupdf_version, mupdf_version, pymupdf_date2)
VersionFitz = mupdf_version
VersionBind = pymupdf_version
VersionDate = pymupdf_date
# String formatting.
def _format_g(value, *, fmt='%g'):
'''
Returns `value` formatted with mupdf.fz_format_double() if available,
otherwise with Python's `%`.
If `value` is a list or tuple, we return a space-separated string of
formatted values.
'''
if isinstance(value, (list, tuple)):
ret = ''
for v in value:
if ret:
ret += ' '
ret += _format_g(v, fmt=fmt)
return ret
else:
if mupdf_version_tuple >= (1, 24, 2):
return mupdf.fz_format_double(fmt, value)
else:
return fmt % value
format_g = _format_g
# Names required by class method typing annotations.
OptBytes = typing.Optional[typing.ByteString]
OptDict = typing.Optional[dict]
OptFloat = typing.Optional[float]
OptInt = typing.Union[int, None]
OptSeq = typing.Optional[typing.Sequence]
OptStr = typing.Optional[str]
Page = 'Page_forward_decl'
Point = 'Point_forward_decl'
TESSDATA_PREFIX = os.environ.get("TESSDATA_PREFIX")
matrix_like = 'matrix_like'
point_like = 'point_like'
quad_like = 'quad_like'
rect_like = 'rect_like'
def _as_fz_document(document):
'''
Returns document as a mupdf.FzDocument, upcasting as required. Raises
'document closed' exception if closed.
'''
if isinstance(document, Document):
if document.is_closed:
raise ValueError('document closed')
document = document.this
if isinstance(document, mupdf.FzDocument):
return document
elif isinstance(document, mupdf.PdfDocument):
return document.super()
elif document is None:
assert 0, f'document is None'
else:
assert 0, f'Unrecognised {type(document)=}'
def _as_pdf_document(document, required=True):
'''
Returns `document` downcast to a mupdf.PdfDocument. If downcast fails (i.e.
`document` is not actually a `PdfDocument`) then we assert-fail if `required`
is true (the default) else return a `mupdf.PdfDocument` with `.m_internal`
false.
'''
if isinstance(document, Document):
if document.is_closed:
raise ValueError('document closed')
document = document.this
if isinstance(document, mupdf.PdfDocument):
return document
elif isinstance(document, mupdf.FzDocument):
ret = mupdf.PdfDocument(document)
if required:
assert ret.m_internal
return ret
elif document is None:
assert 0, f'document is None'
else:
assert 0, f'Unrecognised {type(document)=}'
def _as_fz_page(page):
'''
Returns page as a mupdf.FzPage, upcasting as required.
'''
if isinstance(page, Page):
page = page.this
if isinstance(page, mupdf.PdfPage):
return page.super()
elif isinstance(page, mupdf.FzPage):
return page
elif page is None:
assert 0, f'page is None'
else:
assert 0, f'Unrecognised {type(page)=}'
def _as_pdf_page(page, required=True):
'''
Returns `page` downcast to a mupdf.PdfPage. If downcast fails (i.e. `page`
is not actually a `PdfPage`) then we assert-fail if `required` is true (the
default) else return a `mupdf.PdfPage` with `.m_internal` false.
'''
if isinstance(page, Page):
page = page.this
if isinstance(page, mupdf.PdfPage):
return page
elif isinstance(page, mupdf.FzPage):
ret = mupdf.pdf_page_from_fz_page(page)
if required:
assert ret.m_internal
return ret
elif page is None:
assert 0, f'page is None'
else:
assert 0, f'Unrecognised {type(page)=}'
# Fixme: we don't support JM_MEMORY=1.
JM_MEMORY = 0
# Classes
#
class Annot:
def __init__(self, annot):
assert isinstance( annot, mupdf.PdfAnnot)
self.this = annot
def __repr__(self):
parent = getattr(self, 'parent', '<>')
return "'%s' annotation on %s" % (self.type[1], str(parent))
def __str__(self):
return self.__repr__()
def _erase(self):
if getattr(self, "thisown", False):
self.thisown = False
def _get_redact_values(self):
annot = self.this
if mupdf.pdf_annot_type(annot) != mupdf.PDF_ANNOT_REDACT:
return
values = dict()
try:
obj = mupdf.pdf_dict_gets(mupdf.pdf_annot_obj(annot), "RO")
if obj.m_internal:
message_warning("Ignoring redaction key '/RO'.")
xref = mupdf.pdf_to_num(obj)
values[dictkey_xref] = xref
obj = mupdf.pdf_dict_gets(mupdf.pdf_annot_obj(annot), "OverlayText")
if obj.m_internal:
text = mupdf.pdf_to_text_string(obj)
values[dictkey_text] = JM_UnicodeFromStr(text)
else:
values[dictkey_text] = ''
obj = mupdf.pdf_dict_get(mupdf.pdf_annot_obj(annot), PDF_NAME('Q'))
align = 0
if obj.m_internal:
align = mupdf.pdf_to_int(obj)
values[dictkey_align] = align
except Exception:
if g_exceptions_verbose: exception_info()
return
val = values
if not val:
return val
val["rect"] = self.rect
text_color, fontname, fontsize = TOOLS._parse_da(self)
val["text_color"] = text_color
val["fontname"] = fontname
val["fontsize"] = fontsize
fill = self.colors["fill"]
val["fill"] = fill
return val
def _getAP(self):
if g_use_extra:
assert isinstance( self.this, mupdf.PdfAnnot)
ret = extra.Annot_getAP(self.this)
assert isinstance( ret, bytes)
return ret
else:
r = None
res = None
annot = self.this
assert isinstance( annot, mupdf.PdfAnnot)
annot_obj = mupdf.pdf_annot_obj( annot)
ap = mupdf.pdf_dict_getl( annot_obj, PDF_NAME('AP'), PDF_NAME('N'))
if mupdf.pdf_is_stream( ap):
res = mupdf.pdf_load_stream( ap)
if res and res.m_internal:
r = JM_BinFromBuffer(res)
return r
def _setAP(self, buffer_, rect=0):
try:
annot = self.this
annot_obj = mupdf.pdf_annot_obj( annot)
page = mupdf.pdf_annot_page( annot)
apobj = mupdf.pdf_dict_getl( annot_obj, PDF_NAME('AP'), PDF_NAME('N'))
if not apobj.m_internal:
raise RuntimeError( MSG_BAD_APN)
if not mupdf.pdf_is_stream( apobj):
raise RuntimeError( MSG_BAD_APN)
res = JM_BufferFromBytes( buffer_)
if not res.m_internal:
raise ValueError( MSG_BAD_BUFFER)
JM_update_stream( page.doc(), apobj, res, 1)
if rect:
bbox = mupdf.pdf_dict_get_rect( annot_obj, PDF_NAME('Rect'))
mupdf.pdf_dict_put_rect( apobj, PDF_NAME('BBox'), bbox)
except Exception:
if g_exceptions_verbose: exception_info()
def _update_appearance(self, opacity=-1, blend_mode=None, fill_color=None, rotate=-1):
annot = self.this
assert annot.m_internal
annot_obj = mupdf.pdf_annot_obj( annot)
page = mupdf.pdf_annot_page( annot)
pdf = page.doc()
type_ = mupdf.pdf_annot_type( annot)
nfcol, fcol = JM_color_FromSequence(fill_color)
try:
# remove fill color from unsupported annots
# or if so requested
if nfcol == 0 or type_ not in (
mupdf.PDF_ANNOT_SQUARE,
mupdf.PDF_ANNOT_CIRCLE,
mupdf.PDF_ANNOT_LINE,
mupdf.PDF_ANNOT_POLY_LINE,
mupdf.PDF_ANNOT_POLYGON
):
mupdf.pdf_dict_del( annot_obj, PDF_NAME('IC'))
elif nfcol > 0:
mupdf.pdf_set_annot_interior_color( annot, fcol[:nfcol])
insert_rot = 1 if rotate >= 0 else 0
if type_ not in (
mupdf.PDF_ANNOT_CARET,
mupdf.PDF_ANNOT_CIRCLE,
mupdf.PDF_ANNOT_FREE_TEXT,
mupdf.PDF_ANNOT_FILE_ATTACHMENT,
mupdf.PDF_ANNOT_INK,
mupdf.PDF_ANNOT_LINE,
mupdf.PDF_ANNOT_POLY_LINE,
mupdf.PDF_ANNOT_POLYGON,
mupdf.PDF_ANNOT_SQUARE,
mupdf.PDF_ANNOT_STAMP,
mupdf.PDF_ANNOT_TEXT,
):
insert_rot = 0
if insert_rot:
mupdf.pdf_dict_put_int( annot_obj, PDF_NAME('Rotate'), rotate)
mupdf.pdf_dirty_annot( annot)
mupdf.pdf_update_annot( annot) # let MuPDF update
pdf.resynth_required = 0
# insert fill color
if type_ == mupdf.PDF_ANNOT_FREE_TEXT:
if nfcol > 0:
mupdf.pdf_set_annot_color( annot, fcol[:nfcol])
elif nfcol > 0:
col = mupdf.pdf_new_array( page.doc(), nfcol)
for i in range( nfcol):
mupdf.pdf_array_push_real( col, fcol[i])
mupdf.pdf_dict_put( annot_obj, PDF_NAME('IC'), col)
except Exception as e:
if g_exceptions_verbose: exception_info()
message( f'cannot update annot: {e}')
raise
if (opacity < 0 or opacity >= 1) and not blend_mode: # no opacity, no blend_mode
return True
try: # create or update /ExtGState
ap = mupdf.pdf_dict_getl(
mupdf.pdf_annot_obj(annot),
PDF_NAME('AP'),
PDF_NAME('N')
)
if not ap.m_internal: # should never happen
raise RuntimeError( MSG_BAD_APN)
resources = mupdf.pdf_dict_get( ap, PDF_NAME('Resources'))
if not resources.m_internal: # no Resources yet: make one
resources = mupdf.pdf_dict_put_dict( ap, PDF_NAME('Resources'), 2)
alp0 = mupdf.pdf_new_dict( page.doc(), 3)
if opacity >= 0 and opacity < 1:
mupdf.pdf_dict_put_real( alp0, PDF_NAME('CA'), opacity)
mupdf.pdf_dict_put_real( alp0, PDF_NAME('ca'), opacity)
mupdf.pdf_dict_put_real( annot_obj, PDF_NAME('CA'), opacity)
if blend_mode:
mupdf.pdf_dict_put_name( alp0, PDF_NAME('BM'), blend_mode)
mupdf.pdf_dict_put_name( annot_obj, PDF_NAME('BM'), blend_mode)
extg = mupdf.pdf_dict_get( resources, PDF_NAME('ExtGState'))
if not extg.m_internal: # no ExtGState yet: make one
extg = mupdf.pdf_dict_put_dict( resources, PDF_NAME('ExtGState'), 2)
mupdf.pdf_dict_put( extg, PDF_NAME('H'), alp0)
except Exception as e:
if g_exceptions_verbose: exception_info()
message( f'cannot set opacity or blend mode\n: {e}')
raise
return True
@property
def apn_bbox(self):
"""annotation appearance bbox"""
CheckParent(self)
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
ap = mupdf.pdf_dict_getl(annot_obj, PDF_NAME('AP'), PDF_NAME('N'))
if not ap.m_internal:
val = JM_py_from_rect(mupdf.FzRect(mupdf.FzRect.Fixed_INFINITE))
else:
rect = mupdf.pdf_dict_get_rect(ap, PDF_NAME('BBox'))
val = JM_py_from_rect(rect)
val = Rect(val) * self.get_parent().transformation_matrix
val *= self.get_parent().derotation_matrix
return val
@property
def apn_matrix(self):
"""annotation appearance matrix"""
try:
CheckParent(self)
annot = self.this
assert isinstance(annot, mupdf.PdfAnnot)
ap = mupdf.pdf_dict_getl(
mupdf.pdf_annot_obj(annot),
mupdf.PDF_ENUM_NAME_AP,
mupdf.PDF_ENUM_NAME_N
)
if not ap.m_internal:
return JM_py_from_matrix(mupdf.FzMatrix())
mat = mupdf.pdf_dict_get_matrix(ap, mupdf.PDF_ENUM_NAME_Matrix)
val = JM_py_from_matrix(mat)
val = Matrix(val)
return val
except Exception:
if g_exceptions_verbose: exception_info()
raise
@property
def blendmode(self):
"""annotation BlendMode"""
CheckParent(self)
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
obj = mupdf.pdf_dict_get(annot_obj, PDF_NAME('BM'))
blend_mode = None
if obj.m_internal:
blend_mode = JM_UnicodeFromStr(mupdf.pdf_to_name(obj))
return blend_mode
# loop through the /AP/N/Resources/ExtGState objects
obj = mupdf.pdf_dict_getl(
annot_obj,
PDF_NAME('AP'),
PDF_NAME('N'),
PDF_NAME('Resources'),
PDF_NAME('ExtGState'),
)
if mupdf.pdf_is_dict(obj):
n = mupdf.pdf_dict_len(obj)
for i in range(n):
obj1 = mupdf.pdf_dict_get_val(obj, i)
if mupdf.pdf_is_dict(obj1):
m = mupdf.pdf_dict_len(obj1)
for j in range(m):
obj2 = mupdf.pdf_dict_get_key(obj1, j)
if mupdf.pdf_objcmp(obj2, PDF_NAME('BM')) == 0:
blend_mode = JM_UnicodeFromStr(mupdf.pdf_to_name(mupdf.pdf_dict_get_val(obj1, j)))
return blend_mode
return blend_mode
@property
def border(self):
"""Border information."""
CheckParent(self)
atype = self.type[0]
if atype not in (
mupdf.PDF_ANNOT_CIRCLE,
mupdf.PDF_ANNOT_FREE_TEXT,
mupdf.PDF_ANNOT_INK,
mupdf.PDF_ANNOT_LINE,
mupdf.PDF_ANNOT_POLY_LINE,
mupdf.PDF_ANNOT_POLYGON,
mupdf.PDF_ANNOT_SQUARE,
):
return dict()
ao = mupdf.pdf_annot_obj(self.this)
ret = JM_annot_border(ao)
return ret
def clean_contents(self, sanitize=1):
"""Clean appearance contents stream."""
CheckParent(self)
annot = self.this
pdf = mupdf.pdf_get_bound_document(mupdf.pdf_annot_obj(annot))
filter_ = _make_PdfFilterOptions(recurse=1, instance_forms=0, ascii=0, sanitize=sanitize)
mupdf.pdf_filter_annot_contents(pdf, annot, filter_)
@property
def colors(self):
"""Color definitions."""
try:
CheckParent(self)
annot = self.this
assert isinstance(annot, mupdf.PdfAnnot)
return JM_annot_colors(mupdf.pdf_annot_obj(annot))
except Exception:
if g_exceptions_verbose: exception_info()
raise
def delete_responses(self):
"""Delete 'Popup' and responding annotations."""
CheckParent(self)
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
page = mupdf.pdf_annot_page(annot)
while 1:
irt_annot = JM_find_annot_irt(annot)
if not irt_annot.m_internal:
break
mupdf.pdf_delete_annot(page, irt_annot)
mupdf.pdf_dict_del(annot_obj, PDF_NAME('Popup'))
annots = mupdf.pdf_dict_get(page.obj(), PDF_NAME('Annots'))
n = mupdf.pdf_array_len(annots)
found = 0
for i in range(n-1, -1, -1):
o = mupdf.pdf_array_get(annots, i)
p = mupdf.pdf_dict_get(o, PDF_NAME('Parent'))
if not o.m_internal:
continue
if not mupdf.pdf_objcmp(p, annot_obj):
mupdf.pdf_array_delete(annots, i)
found = 1
if found:
mupdf.pdf_dict_put(page.obj(), PDF_NAME('Annots'), annots)
@property
def file_info(self):
"""Attached file information."""
CheckParent(self)
res = dict()
length = -1
size = -1
desc = None
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
type_ = mupdf.pdf_annot_type(annot)
if type_ != mupdf.PDF_ANNOT_FILE_ATTACHMENT:
raise TypeError( MSG_BAD_ANNOT_TYPE)
stream = mupdf.pdf_dict_getl(
annot_obj,
PDF_NAME('FS'),
PDF_NAME('EF'),
PDF_NAME('F'),
)
if not stream.m_internal:
RAISEPY( "bad PDF: file entry not found", JM_Exc_FileDataError)
fs = mupdf.pdf_dict_get(annot_obj, PDF_NAME('FS'))
o = mupdf.pdf_dict_get(fs, PDF_NAME('UF'))
if o.m_internal:
filename = mupdf.pdf_to_text_string(o)
else:
o = mupdf.pdf_dict_get(fs, PDF_NAME('F'))
if o.m_internal:
filename = mupdf.pdf_to_text_string(o)
o = mupdf.pdf_dict_get(fs, PDF_NAME('Desc'))
if o.m_internal:
desc = mupdf.pdf_to_text_string(o)
o = mupdf.pdf_dict_get(stream, PDF_NAME('Length'))
if o.m_internal:
length = mupdf.pdf_to_int(o)
o = mupdf.pdf_dict_getl(stream, PDF_NAME('Params'), PDF_NAME('Size'))
if o.m_internal:
size = mupdf.pdf_to_int(o)
res[ dictkey_filename] = JM_EscapeStrFromStr(filename)
res[ dictkey_desc] = JM_UnicodeFromStr(desc)
res[ dictkey_length] = length
res[ dictkey_size] = size
return res
@property
def flags(self):
"""Flags field."""
CheckParent(self)
annot = self.this
return mupdf.pdf_annot_flags(annot)
def get_file(self):
"""Retrieve attached file content."""
CheckParent(self)
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
type = mupdf.pdf_annot_type(annot)
if type != mupdf.PDF_ANNOT_FILE_ATTACHMENT:
raise TypeError( MSG_BAD_ANNOT_TYPE)
stream = mupdf.pdf_dict_getl(annot_obj, PDF_NAME('FS'), PDF_NAME('EF'), PDF_NAME('F'))
if not stream.m_internal:
RAISEPY( "bad PDF: file entry not found", JM_Exc_FileDataError)
buf = mupdf.pdf_load_stream(stream)
res = JM_BinFromBuffer(buf)
return res
def get_oc(self):
"""Get annotation optional content reference."""
CheckParent(self)
oc = 0
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
obj = mupdf.pdf_dict_get(annot_obj, PDF_NAME('OC'))
if obj.m_internal:
oc = mupdf.pdf_to_num(obj)
return oc
# PyMuPDF doesn't seem to have this .parent member, but removing it breaks
# 11 tests...?
#@property
def get_parent(self):
try:
ret = getattr( self, 'parent')
except AttributeError:
page = mupdf.pdf_annot_page(self.this)
assert isinstance( page, mupdf.PdfPage)
document = Document( page.doc()) if page.m_internal else None
ret = Page(page, document)
#self.parent = weakref.proxy( ret)
self.parent = ret
#log(f'No attribute .parent: {type(self)=} {id(self)=}: have set {id(self.parent)=}.')
#log( f'Have set self.parent')
return ret
def get_pixmap(self, matrix=None, dpi=None, colorspace=None, alpha=0):
"""annotation Pixmap"""
CheckParent(self)
cspaces = {"gray": csGRAY, "rgb": csRGB, "cmyk": csCMYK}
if type(colorspace) is str:
colorspace = cspaces.get(colorspace.lower(), None)
if dpi:
matrix = Matrix(dpi / 72, dpi / 72)
ctm = JM_matrix_from_py(matrix)
cs = colorspace
if not cs:
cs = mupdf.fz_device_rgb()
pix = mupdf.pdf_new_pixmap_from_annot(self.this, ctm, cs, mupdf.FzSeparations(0), alpha)
ret = Pixmap(pix)
if dpi:
ret.set_dpi(dpi, dpi)
return ret
def get_sound(self):
"""Retrieve sound stream."""
CheckParent(self)
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
type = mupdf.pdf_annot_type(annot)
sound = mupdf.pdf_dict_get(annot_obj, PDF_NAME('Sound'))
if type != mupdf.PDF_ANNOT_SOUND or not sound.m_internal:
raise TypeError( MSG_BAD_ANNOT_TYPE)
if mupdf.pdf_dict_get(sound, PDF_NAME('F')).m_internal:
RAISEPY( "unsupported sound stream", JM_Exc_FileDataError)
res = dict()
obj = mupdf.pdf_dict_get(sound, PDF_NAME('R'))
if obj.m_internal:
res['rate'] = mupdf.pdf_to_real(obj)
obj = mupdf.pdf_dict_get(sound, PDF_NAME('C'))
if obj.m_internal:
res['channels'] = mupdf.pdf_to_int(obj)
obj = mupdf.pdf_dict_get(sound, PDF_NAME('B'))
if obj.m_internal:
res['bps'] = mupdf.pdf_to_int(obj)
obj = mupdf.pdf_dict_get(sound, PDF_NAME('E'))
if obj.m_internal:
res['encoding'] = mupdf.pdf_to_name(obj)
obj = mupdf.pdf_dict_gets(sound, "CO")
if obj.m_internal:
res['compression'] = mupdf.pdf_to_name(obj)
buf = mupdf.pdf_load_stream(sound)
stream = JM_BinFromBuffer(buf)
res['stream'] = stream
return res
def get_textpage(self, clip=None, flags=0):
"""Make annotation TextPage."""
CheckParent(self)
options = mupdf.FzStextOptions()
options.flags = flags
annot = self.this
stextpage = mupdf.FzStextPage(annot, options)
ret = TextPage(stextpage)
p = self.get_parent()
if isinstance(p, weakref.ProxyType):
ret.parent = p
else:
ret.parent = weakref.proxy(p)
return ret
@property
def has_popup(self):
"""Check if annotation has a Popup."""
CheckParent(self)
annot = self.this
obj = mupdf.pdf_dict_get(mupdf.pdf_annot_obj(annot), PDF_NAME('Popup'))
return True if obj.m_internal else False
@property
def info(self):
"""Various information details."""
CheckParent(self)
annot = self.this
res = dict()
res[dictkey_content] = JM_UnicodeFromStr(mupdf.pdf_annot_contents(annot))
o = mupdf.pdf_dict_get(mupdf.pdf_annot_obj(annot), PDF_NAME('Name'))
res[dictkey_name] = JM_UnicodeFromStr(mupdf.pdf_to_name(o))
# Title (= author)
o = mupdf.pdf_dict_get(mupdf.pdf_annot_obj(annot), PDF_NAME('T'))
res[dictkey_title] = JM_UnicodeFromStr(mupdf.pdf_to_text_string(o))
# CreationDate
o = mupdf.pdf_dict_gets(mupdf.pdf_annot_obj(annot), "CreationDate")
res[dictkey_creationDate] = JM_UnicodeFromStr(mupdf.pdf_to_text_string(o))
# ModDate
o = mupdf.pdf_dict_get(mupdf.pdf_annot_obj(annot), PDF_NAME('M'))
res[dictkey_modDate] = JM_UnicodeFromStr(mupdf.pdf_to_text_string(o))
# Subj
o = mupdf.pdf_dict_gets(mupdf.pdf_annot_obj(annot), "Subj")
res[dictkey_subject] = mupdf.pdf_to_text_string(o)
# Identification (PDF key /NM)
o = mupdf.pdf_dict_gets(mupdf.pdf_annot_obj(annot), "NM")
res[dictkey_id] = JM_UnicodeFromStr(mupdf.pdf_to_text_string(o))
return res
@property
def irt_xref(self):
'''
annotation IRT xref
'''
annot = self.this
annot_obj = mupdf.pdf_annot_obj( annot)
irt = mupdf.pdf_dict_get( annot_obj, PDF_NAME('IRT'))
if not irt.m_internal:
return 0
return mupdf.pdf_to_num( irt)
@property
def is_open(self):
"""Get 'open' status of annotation or its Popup."""
CheckParent(self)
return mupdf.pdf_annot_is_open(self.this)
@property
def language(self):
"""annotation language"""
this_annot = self.this
lang = mupdf.pdf_annot_language(this_annot)
if lang == mupdf.FZ_LANG_UNSET:
return
assert hasattr(mupdf, 'fz_string_from_text_language2')
return mupdf.fz_string_from_text_language2(lang)
@property
def line_ends(self):
"""Line end codes."""
CheckParent(self)
annot = self.this
# return nothing for invalid annot types
if not mupdf.pdf_annot_has_line_ending_styles(annot):
return
lstart = mupdf.pdf_annot_line_start_style(annot)
lend = mupdf.pdf_annot_line_end_style(annot)
return lstart, lend
@property
def next(self):
"""Next annotation."""
CheckParent(self)
this_annot = self.this
assert isinstance(this_annot, mupdf.PdfAnnot)
assert this_annot.m_internal
type_ = mupdf.pdf_annot_type(this_annot)
if type_ != mupdf.PDF_ANNOT_WIDGET:
annot = mupdf.pdf_next_annot(this_annot)
else:
annot = mupdf.pdf_next_widget(this_annot)
val = Annot(annot) if annot.m_internal else None
if not val:
return None
val.thisown = True
assert val.get_parent().this.m_internal_value() == self.get_parent().this.m_internal_value()
val.parent._annot_refs[id(val)] = val
if val.type[0] == mupdf.PDF_ANNOT_WIDGET:
widget = Widget()
TOOLS._fill_widget(val, widget)
val = widget
return val
@property
def opacity(self):
"""Opacity."""
CheckParent(self)
annot = self.this
opy = -1
ca = mupdf.pdf_dict_get( mupdf.pdf_annot_obj(annot), mupdf.PDF_ENUM_NAME_CA)
if mupdf.pdf_is_number(ca):
opy = mupdf.pdf_to_real(ca)
return opy
@property
def popup_rect(self):
"""annotation 'Popup' rectangle"""
CheckParent(self)
rect = mupdf.FzRect(mupdf.FzRect.Fixed_INFINITE)
annot = self.this
annot_obj = mupdf.pdf_annot_obj( annot)
obj = mupdf.pdf_dict_get( annot_obj, PDF_NAME('Popup'))
if obj.m_internal:
rect = mupdf.pdf_dict_get_rect(obj, PDF_NAME('Rect'))
#log( '{rect=}')
val = JM_py_from_rect(rect)
#log( '{val=}')
val = Rect(val) * self.get_parent().transformation_matrix
val *= self.get_parent().derotation_matrix
return val
@property
def popup_xref(self):
"""annotation 'Popup' xref"""
CheckParent(self)
xref = 0
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
obj = mupdf.pdf_dict_get(annot_obj, PDF_NAME('Popup'))
if obj.m_internal:
xref = mupdf.pdf_to_num(obj)
return xref
@property
def rect(self):
"""annotation rectangle"""
if g_use_extra:
val = extra.Annot_rect3( self.this)
else:
val = mupdf.pdf_bound_annot(self.this)
val = Rect(val)
# Caching self.parent_() reduces 1000x from 0.07 to 0.04.
#
p = self.get_parent()
#p = getattr( self, 'parent', None)
#if p is None:
# p = self.parent
# self.parent = p
#p = self.parent_()
val *= p.derotation_matrix
return val
@property
def rect_delta(self):
'''
annotation delta values to rectangle
'''
annot_obj = mupdf.pdf_annot_obj(self.this)
arr = mupdf.pdf_dict_get( annot_obj, PDF_NAME('RD'))
if mupdf.pdf_array_len( arr) == 4:
return (
mupdf.pdf_to_real( mupdf.pdf_array_get( arr, 0)),
mupdf.pdf_to_real( mupdf.pdf_array_get( arr, 1)),
-mupdf.pdf_to_real( mupdf.pdf_array_get( arr, 2)),
-mupdf.pdf_to_real( mupdf.pdf_array_get( arr, 3)),
)
@property
def rotation(self):
"""annotation rotation"""
CheckParent(self)
annot = self.this
rotation = mupdf.pdf_dict_get( mupdf.pdf_annot_obj(annot), mupdf.PDF_ENUM_NAME_Rotate)
if not rotation.m_internal:
return -1
return mupdf.pdf_to_int( rotation)
def set_apn_bbox(self, bbox):
"""
Set annotation appearance bbox.
"""
CheckParent(self)
page = self.get_parent()
rot = page.rotation_matrix
mat = page.transformation_matrix
bbox *= rot * ~mat
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
ap = mupdf.pdf_dict_getl(annot_obj, PDF_NAME('AP'), PDF_NAME('N'))
if not ap.m_internal:
raise RuntimeError( MSG_BAD_APN)
rect = JM_rect_from_py(bbox)
mupdf.pdf_dict_put_rect(ap, PDF_NAME('BBox'), rect)
def set_apn_matrix(self, matrix):
"""Set annotation appearance matrix."""
CheckParent(self)
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
ap = mupdf.pdf_dict_getl(annot_obj, PDF_NAME('AP'), PDF_NAME('N'))
if not ap.m_internal:
raise RuntimeError( MSG_BAD_APN)
mat = JM_matrix_from_py(matrix)
mupdf.pdf_dict_put_matrix(ap, PDF_NAME('Matrix'), mat)
def set_blendmode(self, blend_mode):
"""Set annotation BlendMode."""
CheckParent(self)
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
mupdf.pdf_dict_put_name(annot_obj, PDF_NAME('BM'), blend_mode)
def set_border(self, border=None, width=-1, style=None, dashes=None, clouds=-1):
"""Set border properties.
Either a dict, or direct arguments width, style, dashes or clouds."""
CheckParent(self)
atype, atname = self.type[:2] # annotation type
if atype not in (
mupdf.PDF_ANNOT_CIRCLE,
mupdf.PDF_ANNOT_FREE_TEXT,
mupdf.PDF_ANNOT_INK,
mupdf.PDF_ANNOT_LINE,
mupdf.PDF_ANNOT_POLY_LINE,
mupdf.PDF_ANNOT_POLYGON,
mupdf.PDF_ANNOT_SQUARE,
):
message(f"Cannot set border for '{atname}'.")
return None
if atype not in (
mupdf.PDF_ANNOT_CIRCLE,
mupdf.PDF_ANNOT_FREE_TEXT,
mupdf.PDF_ANNOT_POLYGON,
mupdf.PDF_ANNOT_SQUARE,
):
if clouds > 0:
message(f"Cannot set cloudy border for '{atname}'.")
clouds = -1 # do not set border effect
if type(border) is not dict:
border = {"width": width, "style": style, "dashes": dashes, "clouds": clouds}
border.setdefault("width", -1)
border.setdefault("style", None)
border.setdefault("dashes", None)
border.setdefault("clouds", -1)
if border["width"] is None:
border["width"] = -1
if border["clouds"] is None:
border["clouds"] = -1
if hasattr(border["dashes"], "__getitem__"): # ensure sequence items are integers
border["dashes"] = tuple(border["dashes"])
for item in border["dashes"]:
if not isinstance(item, int):
border["dashes"] = None
break
annot = self.this
annot_obj = mupdf.pdf_annot_obj( annot)
pdf = mupdf.pdf_get_bound_document( annot_obj)
return JM_annot_set_border( border, pdf, annot_obj)
def set_colors(self, colors=None, stroke=None, fill=None):
"""Set 'stroke' and 'fill' colors.
Use either a dict or the direct arguments.
"""
CheckParent(self)
doc = self.get_parent().parent
if type(colors) is not dict:
colors = {"fill": fill, "stroke": stroke}
fill = colors.get("fill")
stroke = colors.get("stroke")
fill_annots = (mupdf.PDF_ANNOT_CIRCLE, mupdf.PDF_ANNOT_SQUARE, mupdf.PDF_ANNOT_LINE, mupdf.PDF_ANNOT_POLY_LINE, mupdf.PDF_ANNOT_POLYGON,
mupdf.PDF_ANNOT_REDACT,)
if stroke in ([], ()):
doc.xref_set_key(self.xref, "C", "[]")
elif stroke is not None:
if hasattr(stroke, "__float__"):
stroke = [float(stroke)]
CheckColor(stroke)
assert len(stroke) in (1, 3, 4)
s = f"[{_format_g(stroke)}]"
doc.xref_set_key(self.xref, "C", s)
if fill and self.type[0] not in fill_annots:
message("Warning: fill color ignored for annot type '%s'." % self.type[1])
return
if fill in ([], ()):
doc.xref_set_key(self.xref, "IC", "[]")
elif fill is not None:
if hasattr(fill, "__float__"):
fill = [float(fill)]
CheckColor(fill)
assert len(fill) in (1, 3, 4)
s = f"[{_format_g(fill)}]"
doc.xref_set_key(self.xref, "IC", s)
def set_flags(self, flags):
"""Set annotation flags."""
CheckParent(self)
annot = self.this
mupdf.pdf_set_annot_flags(annot, flags)
def set_info(self, info=None, content=None, title=None, creationDate=None, modDate=None, subject=None):
"""Set various properties."""
CheckParent(self)
if type(info) is dict: # build the args from the dictionary
content = info.get("content", None)
title = info.get("title", None)
creationDate = info.get("creationDate", None)
modDate = info.get("modDate", None)
subject = info.get("subject", None)
info = None
annot = self.this
# use this to indicate a 'markup' annot type
is_markup = mupdf.pdf_annot_has_author(annot)
# contents
if content:
mupdf.pdf_set_annot_contents(annot, content)
if is_markup:
# title (= author)
if title:
mupdf.pdf_set_annot_author(annot, title)
# creation date
if creationDate:
mupdf.pdf_dict_put_text_string(mupdf.pdf_annot_obj(annot), PDF_NAME('CreationDate'), creationDate)
# mod date
if modDate:
mupdf.pdf_dict_put_text_string(mupdf.pdf_annot_obj(annot), PDF_NAME('M'), modDate)
# subject
if subject:
mupdf.pdf_dict_puts(mupdf.pdf_annot_obj(annot), "Subj", mupdf.pdf_new_text_string(subject))
def set_irt_xref(self, xref):
'''
Set annotation IRT xref
'''
annot = self.this
annot_obj = mupdf.pdf_annot_obj( annot)
page = mupdf.pdf_annot_page( annot)
if xref < 1 or xref >= mupdf.pdf_xref_len( page.doc()):
raise ValueError( MSG_BAD_XREF)
irt = mupdf.pdf_new_indirect( page.doc(), xref, 0)
subt = mupdf.pdf_dict_get( irt, PDF_NAME('Subtype'))
irt_subt = mupdf.pdf_annot_type_from_string( mupdf.pdf_to_name( subt))
if irt_subt < 0:
raise ValueError( MSG_IS_NO_ANNOT)
mupdf.pdf_dict_put( annot_obj, PDF_NAME('IRT'), irt)
def set_language(self, language=None):
"""Set annotation language."""
CheckParent(self)
this_annot = self.this
if not language:
lang = mupdf.FZ_LANG_UNSET
else:
lang = mupdf.fz_text_language_from_string(language)
mupdf.pdf_set_annot_language(this_annot, lang)
def set_line_ends(self, start, end):
"""Set line end codes."""
CheckParent(self)
annot = self.this
if mupdf.pdf_annot_has_line_ending_styles(annot):
mupdf.pdf_set_annot_line_ending_styles(annot, start, end)
else:
message_warning("bad annot type for line ends")
def set_name(self, name):
"""Set /Name (icon) of annotation."""
CheckParent(self)
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
mupdf.pdf_dict_put_name(annot_obj, PDF_NAME('Name'), name)
def set_oc(self, oc=0):
"""Set / remove annotation OC xref."""
CheckParent(self)
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
if not oc:
mupdf.pdf_dict_del(annot_obj, PDF_NAME('OC'))
else:
JM_add_oc_object(mupdf.pdf_get_bound_document(annot_obj), annot_obj, oc)
def set_opacity(self, opacity):
"""Set opacity."""
CheckParent(self)
annot = self.this
if not _INRANGE(opacity, 0.0, 1.0):
mupdf.pdf_set_annot_opacity(annot, 1)
return
mupdf.pdf_set_annot_opacity(annot, opacity)
if opacity < 1.0:
page = mupdf.pdf_annot_page(annot)
page.transparency = 1
def set_open(self, is_open):
"""Set 'open' status of annotation or its Popup."""
CheckParent(self)
annot = self.this
mupdf.pdf_set_annot_is_open(annot, is_open)
def set_popup(self, rect):
'''
Create annotation 'Popup' or update rectangle.
'''
CheckParent(self)
annot = self.this
pdfpage = mupdf.pdf_annot_page( annot)
rot = JM_rotate_page_matrix(pdfpage)
r = mupdf.fz_transform_rect(JM_rect_from_py(rect), rot)
mupdf.pdf_set_annot_popup(annot, r)
def set_rect(self, rect):
"""Set annotation rectangle."""
CheckParent(self)
annot = self.this
pdfpage = mupdf.pdf_annot_page(annot)
rot = JM_rotate_page_matrix(pdfpage)
r = mupdf.fz_transform_rect(JM_rect_from_py(rect), rot)
if mupdf.fz_is_empty_rect(r) or mupdf.fz_is_infinite_rect(r):
raise ValueError( MSG_BAD_RECT)
try:
mupdf.pdf_set_annot_rect(annot, r)
except Exception as e:
message(f'cannot set rect: {e}')
return False
def set_rotation(self, rotate=0):
"""Set annotation rotation."""
CheckParent(self)
annot = self.this
type = mupdf.pdf_annot_type(annot)
if type not in (
mupdf.PDF_ANNOT_CARET,
mupdf.PDF_ANNOT_CIRCLE,
mupdf.PDF_ANNOT_FREE_TEXT,
mupdf.PDF_ANNOT_FILE_ATTACHMENT,
mupdf.PDF_ANNOT_INK,
mupdf.PDF_ANNOT_LINE,
mupdf.PDF_ANNOT_POLY_LINE,
mupdf.PDF_ANNOT_POLYGON,
mupdf.PDF_ANNOT_SQUARE,
mupdf.PDF_ANNOT_STAMP,
mupdf.PDF_ANNOT_TEXT,
):
return
rot = rotate
while rot < 0:
rot += 360
while rot >= 360:
rot -= 360
if type == mupdf.PDF_ANNOT_FREE_TEXT and rot % 90 != 0:
rot = 0
annot_obj = mupdf.pdf_annot_obj(annot)
mupdf.pdf_dict_put_int(annot_obj, PDF_NAME('Rotate'), rot)
@property
def type(self):
"""annotation type"""
CheckParent(self)
if not self.this.m_internal:
return 'null'
type_ = mupdf.pdf_annot_type(self.this)
c = mupdf.pdf_string_from_annot_type(type_)
o = mupdf.pdf_dict_gets( mupdf.pdf_annot_obj(self.this), 'IT')
if not o.m_internal or mupdf.pdf_is_name(o):
return (type_, c)
it = mupdf.pdf_to_name(o)
return (type_, c, it)
def update(self,
blend_mode: OptStr =None,
opacity: OptFloat =None,
fontsize: float =0,
fontname: OptStr =None,
text_color: OptSeq =None,
border_color: OptSeq =None,
fill_color: OptSeq =None,
cross_out: bool =True,
rotate: int =-1,
):
"""Update annot appearance.
Notes:
Depending on the annot type, some parameters make no sense,
while others are only available in this method to achieve the
desired result. This is especially true for 'FreeText' annots.
Args:
blend_mode: set the blend mode, all annotations.
opacity: set the opacity, all annotations.
fontsize: set fontsize, 'FreeText' only.
fontname: set the font, 'FreeText' only.
border_color: set border color, 'FreeText' only.
text_color: set text color, 'FreeText' only.
fill_color: set fill color, all annotations.
cross_out: draw diagonal lines, 'Redact' only.
rotate: set rotation, 'FreeText' and some others.
"""
Annot.update_timing_test()
CheckParent(self)
def color_string(cs, code):
"""Return valid PDF color operator for a given color sequence.
"""
cc = ColorCode(cs, code)
if not cc:
return b""
return (cc + "\n").encode()
annot_type = self.type[0] # get the annot type
dt = self.border.get("dashes", None) # get the dashes spec
bwidth = self.border.get("width", -1) # get border line width
stroke = self.colors["stroke"] # get the stroke color
if fill_color is not None:
fill = fill_color
else:
fill = self.colors["fill"]
rect = None # self.rect # prevent MuPDF fiddling with it
apnmat = self.apn_matrix # prevent MuPDF fiddling with it
if rotate != -1: # sanitize rotation value
while rotate < 0:
rotate += 360
while rotate >= 360:
rotate -= 360
if annot_type == mupdf.PDF_ANNOT_FREE_TEXT and rotate % 90 != 0:
rotate = 0
#------------------------------------------------------------------
# handle opacity and blend mode
#------------------------------------------------------------------
if blend_mode is None:
blend_mode = self.blendmode
if not hasattr(opacity, "__float__"):
opacity = self.opacity
if 0 <= opacity < 1 or blend_mode is not None:
opa_code = "/H gs\n" # then we must reference this 'gs'
else:
opa_code = ""
if annot_type == mupdf.PDF_ANNOT_FREE_TEXT:
CheckColor(border_color)
CheckColor(text_color)
CheckColor(fill_color)
tcol, fname, fsize = TOOLS._parse_da(self)
# read and update default appearance as necessary
update_default_appearance = False
if fsize <= 0:
fsize = 12
update_default_appearance = True
if text_color is not None:
tcol = text_color
update_default_appearance = True
if fontname is not None:
fname = fontname
update_default_appearance = True
if fontsize > 0:
fsize = fontsize
update_default_appearance = True
if update_default_appearance:
da_str = ""
if len(tcol) == 3:
fmt = "{:g} {:g} {:g} rg /{f:s} {s:g} Tf"
elif len(tcol) == 1:
fmt = "{:g} g /{f:s} {s:g} Tf"
elif len(tcol) == 4:
fmt = "{:g} {:g} {:g} {:g} k /{f:s} {s:g} Tf"
da_str = fmt.format(*tcol, f=fname, s=fsize)
TOOLS._update_da(self, da_str)
#------------------------------------------------------------------
# now invoke MuPDF to update the annot appearance
#------------------------------------------------------------------
val = self._update_appearance(
opacity=opacity,
blend_mode=blend_mode,
fill_color=fill,
rotate=rotate,
)
if val is False:
raise RuntimeError("Error updating annotation.")
bfill = color_string(fill, "f")
bstroke = color_string(stroke, "c")
p_ctm = self.get_parent().transformation_matrix
imat = ~p_ctm # inverse page transf. matrix
if dt:
dashes = "[" + " ".join(map(str, dt)) + "] 0 d\n"
dashes = dashes.encode("utf-8")
else:
dashes = None
if self.line_ends:
line_end_le, line_end_ri = self.line_ends
else:
line_end_le, line_end_ri = 0, 0 # init line end codes
# read contents as created by MuPDF
ap = self._getAP()
ap_tab = ap.splitlines() # split in single lines
ap_updated = False # assume we did nothing
if annot_type == mupdf.PDF_ANNOT_REDACT:
if cross_out: # create crossed-out rect
ap_updated = True
ap_tab = ap_tab[:-1]
_, LL, LR, UR, UL = ap_tab
ap_tab.append(LR)
ap_tab.append(LL)
ap_tab.append(UR)
ap_tab.append(LL)
ap_tab.append(UL)
ap_tab.append(b"S")
if bwidth > 0 or bstroke != b"":
ap_updated = True
ntab = [_format_g(bwidth).encode() + b" w"] if bwidth > 0 else []
for line in ap_tab:
if line.endswith(b"w"):
continue
if line.endswith(b"RG") and bstroke != b"":
line = bstroke[:-1]
ntab.append(line)
ap_tab = ntab
ap = b"\n".join(ap_tab)
if annot_type == mupdf.PDF_ANNOT_FREE_TEXT:
BT = ap.find(b"BT")
ET = ap.rfind(b"ET") + 2
ap = ap[BT:ET]
w, h = self.rect.width, self.rect.height
if rotate in (90, 270) or not (apnmat.b == apnmat.c == 0):
w, h = h, w
re = b"0 0 " + _format_g((w, h)).encode() + b" re"
ap = re + b"\nW\nn\n" + ap
ope = None
fill_string = color_string(fill, "f")
if fill_string:
ope = b"f"
stroke_string = color_string(border_color, "c")
if stroke_string and bwidth > 0:
ope = b"S"
bwidth = _format_g(bwidth).encode() + b" w\n"
else:
bwidth = stroke_string = b""
if fill_string and stroke_string:
ope = b"B"
if ope is not None:
ap = bwidth + fill_string + stroke_string + re + b"\n" + ope + b"\n" + ap
if dashes is not None: # handle dashes
ap = dashes + b"\n" + ap
dashes = None
ap_updated = True
if annot_type in (mupdf.PDF_ANNOT_POLYGON, mupdf.PDF_ANNOT_POLY_LINE):
ap = b"\n".join(ap_tab[:-1]) + b"\n"
ap_updated = True
if bfill != b"":
if annot_type == mupdf.PDF_ANNOT_POLYGON:
ap = ap + bfill + b"b" # close, fill, and stroke
elif annot_type == mupdf.PDF_ANNOT_POLY_LINE:
ap = ap + b"S" # stroke
else:
if annot_type == mupdf.PDF_ANNOT_POLYGON:
ap = ap + b"s" # close and stroke
elif annot_type == mupdf.PDF_ANNOT_POLY_LINE:
ap = ap + b"S" # stroke
if dashes is not None: # handle dashes
ap = dashes + ap
# reset dashing - only applies for LINE annots with line ends given
ap = ap.replace(b"\nS\n", b"\nS\n[] 0 d\n", 1)
ap_updated = True
if opa_code:
ap = opa_code.encode("utf-8") + ap
ap_updated = True
ap = b"q\n" + ap + b"\nQ\n"
#----------------------------------------------------------------------
# the following handles line end symbols for 'Polygon' and 'Polyline'
#----------------------------------------------------------------------
if line_end_le + line_end_ri > 0 and annot_type in (mupdf.PDF_ANNOT_POLYGON, mupdf.PDF_ANNOT_POLY_LINE):
le_funcs = (None, TOOLS._le_square, TOOLS._le_circle,
TOOLS._le_diamond, TOOLS._le_openarrow,
TOOLS._le_closedarrow, TOOLS._le_butt,
TOOLS._le_ropenarrow, TOOLS._le_rclosedarrow,
TOOLS._le_slash)
le_funcs_range = range(1, len(le_funcs))
d = 2 * max(1, self.border["width"])
rect = self.rect + (-d, -d, d, d)
ap_updated = True
points = self.vertices
if line_end_le in le_funcs_range:
p1 = Point(points[0]) * imat
p2 = Point(points[1]) * imat
left = le_funcs[line_end_le](self, p1, p2, False, fill_color)
ap += left.encode()
if line_end_ri in le_funcs_range:
p1 = Point(points[-2]) * imat
p2 = Point(points[-1]) * imat
left = le_funcs[line_end_ri](self, p1, p2, True, fill_color)
ap += left.encode()
if ap_updated:
if rect: # rect modified here?
self.set_rect(rect)
self._setAP(ap, rect=1)
else:
self._setAP(ap, rect=0)
#-------------------------------
# handle annotation rotations
#-------------------------------
if annot_type not in ( # only these types are supported
mupdf.PDF_ANNOT_CARET,
mupdf.PDF_ANNOT_CIRCLE,
mupdf.PDF_ANNOT_FILE_ATTACHMENT,
mupdf.PDF_ANNOT_INK,
mupdf.PDF_ANNOT_LINE,
mupdf.PDF_ANNOT_POLY_LINE,
mupdf.PDF_ANNOT_POLYGON,
mupdf.PDF_ANNOT_SQUARE,
mupdf.PDF_ANNOT_STAMP,
mupdf.PDF_ANNOT_TEXT,
):
return
rot = self.rotation # get value from annot object
if rot == -1: # nothing to change
return
M = (self.rect.tl + self.rect.br) / 2 # center of annot rect
if rot == 0: # undo rotations
if abs(apnmat - Matrix(1, 1)) < 1e-5:
return # matrix already is a no-op
quad = self.rect.morph(M, ~apnmat) # derotate rect
self.setRect(quad.rect)
self.set_apn_matrix(Matrix(1, 1)) # appearance matrix = no-op
return
mat = Matrix(rot)
quad = self.rect.morph(M, mat)
self.set_rect(quad.rect)
self.set_apn_matrix(apnmat * mat)
def update_file(self, buffer_=None, filename=None, ufilename=None, desc=None):
"""Update attached file."""
CheckParent(self)
annot = self.this
annot_obj = mupdf.pdf_annot_obj(annot)
pdf = mupdf.pdf_get_bound_document(annot_obj) # the owning PDF
type = mupdf.pdf_annot_type(annot)
if type != mupdf.PDF_ANNOT_FILE_ATTACHMENT:
raise TypeError( MSG_BAD_ANNOT_TYPE)
stream = mupdf.pdf_dict_getl(annot_obj, PDF_NAME('FS'), PDF_NAME('EF'), PDF_NAME('F'))
# the object for file content
if not stream.m_internal:
RAISEPY( "bad PDF: no /EF object", JM_Exc_FileDataError)
fs = mupdf.pdf_dict_get(annot_obj, PDF_NAME('FS'))
# file content given
res = JM_BufferFromBytes(buffer_)
if buffer_ and not res.m_internal:
raise ValueError( MSG_BAD_BUFFER)
if res:
JM_update_stream(pdf, stream, res, 1)
# adjust /DL and /Size parameters
len, _ = mupdf.fz_buffer_storage(res)
l = mupdf.pdf_new_int(len)
mupdf.pdf_dict_put(stream, PDF_NAME('DL'), l)
mupdf.pdf_dict_putl(stream, l, PDF_NAME('Params'), PDF_NAME('Size'))
if filename:
mupdf.pdf_dict_put_text_string(stream, PDF_NAME('F'), filename)
mupdf.pdf_dict_put_text_string(fs, PDF_NAME('F'), filename)
mupdf.pdf_dict_put_text_string(stream, PDF_NAME('UF'), filename)
mupdf.pdf_dict_put_text_string(fs, PDF_NAME('UF'), filename)
mupdf.pdf_dict_put_text_string(annot_obj, PDF_NAME('Contents'), filename)
if ufilename:
mupdf.pdf_dict_put_text_string(stream, PDF_NAME('UF'), ufilename)
mupdf.pdf_dict_put_text_string(fs, PDF_NAME('UF'), ufilename)
if desc:
mupdf.pdf_dict_put_text_string(stream, PDF_NAME('Desc'), desc)
mupdf.pdf_dict_put_text_string(fs, PDF_NAME('Desc'), desc)
@staticmethod
def update_timing_test():
total = 0
for i in range( 30*1000):
total += i
return total
@property
def vertices(self):
"""annotation vertex points"""
CheckParent(self)
annot = self.this
assert isinstance(annot, mupdf.PdfAnnot)
annot_obj = mupdf.pdf_annot_obj(annot)
page = mupdf.pdf_annot_page(annot)
page_ctm = mupdf.FzMatrix() # page transformation matrix
dummy = mupdf.FzRect() # Out-param for mupdf.pdf_page_transform().
mupdf.pdf_page_transform(page, dummy, page_ctm)
derot = JM_derotate_page_matrix(page)
page_ctm = mupdf.fz_concat(page_ctm, derot)
#----------------------------------------------------------------
# The following objects occur in different annotation types.
# So we are sure that (!o) occurs at most once.
# Every pair of floats is one point, that needs to be separately
# transformed with the page transformation matrix.
#----------------------------------------------------------------
o = mupdf.pdf_dict_get(annot_obj, PDF_NAME('Vertices'))
if not o.m_internal: o = mupdf.pdf_dict_get(annot_obj, PDF_NAME('L'))
if not o.m_internal: o = mupdf.pdf_dict_get(annot_obj, PDF_NAME('QuadPoints'))
if not o.m_internal: o = mupdf.pdf_dict_gets(annot_obj, 'CL')
if o.m_internal:
# handle lists with 1-level depth
# weiter
res = []
for i in range(0, mupdf.pdf_array_len(o), 2):
x = mupdf.pdf_to_real(mupdf.pdf_array_get(o, i))
y = mupdf.pdf_to_real(mupdf.pdf_array_get(o, i+1))
point = mupdf.FzPoint(x, y)
point = mupdf.fz_transform_point(point, page_ctm)
res.append( (point.x, point.y))
return res
o = mupdf.pdf_dict_gets(annot_obj, 'InkList')
if o.m_internal:
# InkList has 2-level lists
#inklist:
res = []
for i in range(mupdf.pdf_array_len(o)):
res1 = []
o1 = mupdf.pdf_array_get(o, i)
for j in range(0, mupdf.pdf_array_len(o1), 2):
x = mupdf.pdf_to_real(mupdf.pdf_array_get(o1, j))
y = mupdf.pdf_to_real(mupdf.pdf_array_get(o1, j+1))
point = mupdf.FzPoint(x, y)
point = mupdf.fz_transform_point(point, page_ctm)
res1.append( (point.x, point.y))
res.append(res1)
return res
@property
def xref(self):
"""annotation xref number"""
CheckParent(self)
annot = self.this
return mupdf.pdf_to_num(mupdf.pdf_annot_obj(annot))
class Archive:
def __init__( self, *args):
'''
Archive(dirname [, path]) - from folder
Archive(file [, path]) - from file name or object
Archive(data, name) - from memory item
Archive() - empty archive
Archive(archive [, path]) - from archive
'''
self._subarchives = list()
self.this = mupdf.fz_new_multi_archive()
if args:
self.add( *args)
def __repr__( self):
return f'Archive, sub-archives: {len(self._subarchives)}'
def _add_arch( self, subarch, path=None):
mupdf.fz_mount_multi_archive( self.this, subarch, path)
def _add_dir( self, folder, path=None):
sub = mupdf.fz_open_directory( folder)
mupdf.fz_mount_multi_archive( self.this, sub, path)
def _add_treeitem( self, memory, name, path=None):
buff = JM_BufferFromBytes( memory)
sub = mupdf.fz_new_tree_archive( mupdf.FzTree())
mupdf.fz_tree_archive_add_buffer( sub, name, buff)
mupdf.fz_mount_multi_archive( self.this, sub, path)
def _add_ziptarfile( self, filepath, type_, path=None):
if type_ == 1:
sub = mupdf.fz_open_zip_archive( filepath)
else:
sub = mupdf.fz_open_tar_archive( filepath)
mupdf.fz_mount_multi_archive( self.this, sub, path)
def _add_ziptarmemory( self, memory, type_, path=None):
buff = JM_BufferFromBytes( memory)
stream = mupdf.fz_open_buffer( buff)
if type_==1:
sub = mupdf.fz_open_zip_archive_with_stream( stream)
else:
sub = mupdf.fz_open_tar_archive_with_stream( stream)
mupdf.fz_mount_multi_archive( self.this, sub, path)
def add( self, content, path=None):
'''
Add a sub-archive.
Args:
content:
The content to be added. May be one of:
`str` - must be path of directory or file.
`bytes`, `bytearray`, `io.BytesIO` - raw data.
`zipfile.Zipfile`.
`tarfile.TarFile`.
`pymupdf.Archive`.
A two-item tuple `(data, name)`.
List or tuple (but not tuple with length 2) of the above.
path: (str) a "virtual" path name, under which the elements
of content can be retrieved. Use it to e.g. cope with
duplicate element names.
'''
def is_binary_data(x):
return isinstance(x, (bytes, bytearray, io.BytesIO))
def make_subarch(entries, mount, fmt):
subarch = dict(fmt=fmt, entries=entries, path=mount)
if fmt != "tree" or self._subarchives == []:
self._subarchives.append(subarch)
else:
ltree = self._subarchives[-1]
if ltree["fmt"] != "tree" or ltree["path"] != subarch["path"]:
self._subarchives.append(subarch)
else:
ltree["entries"].extend(subarch["entries"])
self._subarchives[-1] = ltree
if isinstance(content, pathlib.Path):
content = str(content)
if isinstance(content, str):
if os.path.isdir(content):
self._add_dir(content, path)
return make_subarch(os.listdir(content), path, 'dir')
elif os.path.isfile(content):
assert isinstance(path, str) and path != '', \
f'Need name for binary content, but {path=}.'
with open(content) as f:
ff = f.read()
self._add_treeitem(ff, path)
return make_subarch([path], None, 'tree')
else:
raise ValueError(f'Not a file or directory: {content!r}')
elif is_binary_data(content):
assert isinstance(path, str) and path != '' \
f'Need name for binary content, but {path=}.'
self._add_treeitem(content, path)
return make_subarch([path], None, 'tree')
elif isinstance(content, zipfile.ZipFile):
filename = getattr(content, "filename", None)
if filename is None:
fp = content.fp.getvalue()
self._add_ziptarmemory(fp, 1, path)
else:
self._add_ziptarfile(filename, 1, path)
return make_subarch(content.namelist(), path, 'zip')
elif isinstance(content, tarfile.TarFile):
filename = getattr(content.fileobj, "name", None)
if filename is None:
fp = content.fileobj
if not isinstance(fp, io.BytesIO):
fp = fp.fileobj
self._add_ziptarmemory(fp.getvalue(), 0, path)
else:
self._add_ziptarfile(filename, 0, path)
return make_subarch(content.getnames(), path, 'tar')
elif isinstance(content, Archive):
self._add_arch(content, path)
return make_subarch([], path, 'multi')
if isinstance(content, tuple) and len(content) == 2:
# covers the tree item plus path
data, name = content
assert isinstance(name, str), f'Unexpected {type(name)=}'
if is_binary_data(data):
self._add_treeitem(data, name, path=path)
elif isinstance(data, str):
if os.path.isfile(data):
with open(data, 'rb') as f:
ff = f.read()
self._add_treeitem(ff, name, path=path)
else:
assert 0, f'Unexpected {type(data)=}.'
return make_subarch([name], path, 'tree')
elif hasattr(content, '__getitem__'):
# Deal with sequence of disparate items.
for item in content:
self.add(item, path)
return
else:
raise TypeError(f'Unrecognised type {type(content)}.')
assert 0
@property
def entry_list( self):
'''
List of sub archives.
'''
return self._subarchives
def has_entry( self, name):
return mupdf.fz_has_archive_entry( self.this, name)
def read_entry( self, name):
buff = mupdf.fz_read_archive_entry( self.this, name)
return JM_BinFromBuffer( buff)
class Xml:
def __enter__(self):
return self
def __exit__(self, *args):
pass
def __init__( self, rhs):
if isinstance( rhs, mupdf.FzXml):
self.this = rhs
elif isinstance( str):
buff = mupdf.fz_new_buffer_from_copied_data( rhs)
self.this = mupdf.fz_parse_xml_from_html5( buff)
else:
assert 0, f'Unsupported type for rhs: {type(rhs)}'
def _get_node_tree( self):
def show_node(node, items, shift):
while node is not None:
if node.is_text:
items.append((shift, f'"{node.text}"'))
node = node.next
continue
items.append((shift, f"({node.tagname}"))
for k, v in node.get_attributes().items():
items.append((shift, f"={k} '{v}'"))
child = node.first_child
if child:
items = show_node(child, items, shift + 1)
items.append((shift, f"){node.tagname}"))
node = node.next
return items
shift = 0
items = []
items = show_node(self, items, shift)
return items
def add_bullet_list(self):
"""Add bulleted list ("ul" tag)"""
child = self.create_element("ul")
self.append_child(child)
return child
def add_class(self, text):
"""Set some class via CSS. Replaces complete class spec."""
cls = self.get_attribute_value("class")
if cls is not None and text in cls:
return self
self.remove_attribute("class")
if cls is None:
cls = text
else:
cls += " " + text
self.set_attribute("class", cls)
return self
def add_code(self, text=None):
"""Add a "code" tag"""
child = self.create_element("code")
if type(text) is str:
child.append_child(self.create_text_node(text))
prev = self.span_bottom()
if prev is None:
prev = self
prev.append_child(child)
return self
def add_codeblock(self):
"""Add monospaced lines ("pre" node)"""
child = self.create_element("pre")
self.append_child(child)
return child
def add_description_list(self):
"""Add description list ("dl" tag)"""
child = self.create_element("dl")
self.append_child(child)
return child
def add_division(self):
"""Add "div" tag"""
child = self.create_element("div")
self.append_child(child)
return child
def add_header(self, level=1):
"""Add header tag"""
if level not in range(1, 7):
raise ValueError("Header level must be in [1, 6]")
this_tag = self.tagname
new_tag = f"h{level}"
child = self.create_element(new_tag)
if this_tag not in ("h1", "h2", "h3", "h4", "h5", "h6", "p"):
self.append_child(child)
return child
self.parent.append_child(child)
return child
def add_horizontal_line(self):
"""Add horizontal line ("hr" tag)"""
child = self.create_element("hr")
self.append_child(child)
return child
def add_image(self, name, width=None, height=None, imgfloat=None, align=None):
"""Add image node (tag "img")."""
child = self.create_element("img")
if width is not None:
child.set_attribute("width", f"{width}")
if height is not None:
child.set_attribute("height", f"{height}")
if imgfloat is not None:
child.set_attribute("style", f"float: {imgfloat}")
if align is not None:
child.set_attribute("align", f"{align}")
child.set_attribute("src", f"{name}")
self.append_child(child)
return child
def add_link(self, href, text=None):
"""Add a hyperlink ("a" tag)"""
child = self.create_element("a")
if not isinstance(text, str):
text = href
child.set_attribute("href", href)
child.append_child(self.create_text_node(text))
prev = self.span_bottom()
if prev is None:
prev = self
prev.append_child(child)
return self
def add_list_item(self):
"""Add item ("li" tag) under a (numbered or bulleted) list."""
if self.tagname not in ("ol", "ul"):
raise ValueError("cannot add list item to", self.tagname)
child = self.create_element("li")
self.append_child(child)
return child
def add_number_list(self, start=1, numtype=None):
"""Add numbered list ("ol" tag)"""
child = self.create_element("ol")
if start > 1:
child.set_attribute("start", str(start))
if numtype is not None:
child.set_attribute("type", numtype)
self.append_child(child)
return child
def add_paragraph(self):
"""Add "p" tag"""
child = self.create_element("p")
if self.tagname != "p":
self.append_child(child)
else:
self.parent.append_child(child)
return child
def add_span(self):
child = self.create_element("span")
self.append_child(child)
return child
def add_style(self, text):
"""Set some style via CSS style. Replaces complete style spec."""
style = self.get_attribute_value("style")
if style is not None and text in style:
return self
self.remove_attribute("style")
if style is None:
style = text
else:
style += ";" + text
self.set_attribute("style", style)
return self
def add_subscript(self, text=None):
"""Add a subscript ("sub" tag)"""
child = self.create_element("sub")
if type(text) is str:
child.append_child(self.create_text_node(text))
prev = self.span_bottom()
if prev is None:
prev = self
prev.append_child(child)
return self
def add_superscript(self, text=None):
"""Add a superscript ("sup" tag)"""
child = self.create_element("sup")
if type(text) is str:
child.append_child(self.create_text_node(text))
prev = self.span_bottom()
if prev is None:
prev = self
prev.append_child(child)
return self
def add_text(self, text):
"""Add text. Line breaks are honored."""
lines = text.splitlines()
line_count = len(lines)
prev = self.span_bottom()
if prev is None:
prev = self
for i, line in enumerate(lines):
prev.append_child(self.create_text_node(line))
if i < line_count - 1:
prev.append_child(self.create_element("br"))
return self
def append_child( self, child):
mupdf.fz_dom_append_child( self.this, child.this)
def append_styled_span(self, style):
span = self.create_element("span")
span.add_style(style)
prev = self.span_bottom()
if prev is None:
prev = self
prev.append_child(span)
return prev
def bodytag( self):
return Xml( mupdf.fz_dom_body( self.this))
def clone( self):
ret = mupdf.fz_dom_clone( self.this)
return Xml( ret)
@staticmethod
def color_text(color):
if type(color) is str:
return color
if type(color) is int:
return f"rgb({sRGB_to_rgb(color)})"
if type(color) in (tuple, list):
return f"rgb{tuple(color)}"
return color
def create_element( self, tag):
return Xml( mupdf.fz_dom_create_element( self.this, tag))
def create_text_node( self, text):
return Xml( mupdf.fz_dom_create_text_node( self.this, text))
def debug(self):
"""Print a list of the node tree below self."""
items = self._get_node_tree()
for item in items:
message(" " * item[0] + item[1].replace("\n", "\\n"))
def find( self, tag, att, match):
ret = mupdf.fz_dom_find( self.this, tag, att, match)
if ret.m_internal:
return Xml( ret)
def find_next( self, tag, att, match):
ret = mupdf.fz_dom_find_next( self.this, tag, att, match)
if ret.m_internal:
return Xml( ret)
@property
def first_child( self):
if mupdf.fz_xml_text( self.this):
# text node, has no child.
return
ret = mupdf.fz_dom_first_child( self)
if ret.m_internal:
return Xml( ret)
def get_attribute_value( self, key):
assert key
return mupdf.fz_dom_attribute( self.this, key)
def get_attributes( self):
if mupdf.fz_xml_text( self.this):
# text node, has no attributes.
return
result = dict()
i = 0
while 1:
val, key = mupdf.fz_dom_get_attribute( self.this, i)
if not val or not key:
break
result[ key] = val
i += 1
return result
def insert_after( self, node):
mupdf.fz_dom_insert_after( self.this, node.this)
def insert_before( self, node):
mupdf.fz_dom_insert_before( self.this, node.this)
def insert_text(self, text):
lines = text.splitlines()
line_count = len(lines)
for i, line in enumerate(lines):
self.append_child(self.create_text_node(line))
if i < line_count - 1:
self.append_child(self.create_element("br"))
return self
@property
def is_text(self):
"""Check if this is a text node."""
return self.text is not None
@property
def last_child(self):
"""Return last child node."""
child = self.first_child
if child is None:
return None
while True:
next = child.next
if not next:
return child
child = next
@property
def next( self):
ret = mupdf.fz_dom_next( self.this)
if ret.m_internal:
return Xml( ret)
@property
def parent( self):
ret = mupdf.fz_dom_parent( self.this)
if ret.m_internal:
return Xml( ret)
@property
def previous( self):
ret = mupdf.fz_dom_previous( self.this)
if ret.m_internal:
return Xml( ret)
def remove( self):
mupdf.fz_dom_remove( self.this)
def remove_attribute( self, key):
assert key
mupdf.fz_dom_remove_attribute( self.this, key)
@property
def root( self):
return Xml( mupdf.fz_xml_root( self.this))
def set_align(self, align):
"""Set text alignment via CSS style"""
text = "text-align: %s"
if isinstance( align, str):
t = align
elif align == TEXT_ALIGN_LEFT:
t = "left"
elif align == TEXT_ALIGN_CENTER:
t = "center"
elif align == TEXT_ALIGN_RIGHT:
t = "right"
elif align == TEXT_ALIGN_JUSTIFY:
t = "justify"
else:
raise ValueError(f"Unrecognised {align=}")
text = text % t
self.add_style(text)
return self
def set_attribute( self, key, value):
assert key
mupdf.fz_dom_add_attribute( self.this, key, value)
def set_bgcolor(self, color):
"""Set background color via CSS style"""
text = f"background-color: %s" % self.color_text(color)
self.add_style(text) # does not work on span level
return self
def set_bold(self, val=True):
"""Set bold on / off via CSS style"""
if val:
val="bold"
else:
val="normal"
text = "font-weight: %s" % val
self.append_styled_span(text)
return self
def set_color(self, color):
"""Set text color via CSS style"""
text = f"color: %s" % self.color_text(color)
self.append_styled_span(text)
return self
def set_columns(self, cols):
"""Set number of text columns via CSS style"""
text = f"columns: {cols}"
self.append_styled_span(text)
return self
def set_font(self, font):
"""Set font-family name via CSS style"""
text = "font-family: %s" % font
self.append_styled_span(text)
return self
def set_fontsize(self, fontsize):
"""Set font size name via CSS style"""
if type(fontsize) is str:
px=""
else:
px="px"
text = f"font-size: {fontsize}{px}"
self.append_styled_span(text)
return self
def set_id(self, unique):
"""Set a unique id."""
# check uniqueness
root = self.root
if root.find(None, "id", unique):
raise ValueError(f"id '{unique}' already exists")
self.set_attribute("id", unique)
return self
def set_italic(self, val=True):
"""Set italic on / off via CSS style"""
if val:
val="italic"
else:
val="normal"
text = "font-style: %s" % val
self.append_styled_span(text)
return self
def set_leading(self, leading):
"""Set inter-line spacing value via CSS style - block-level only."""
text = f"-mupdf-leading: {leading}"
self.add_style(text)
return self
def set_letter_spacing(self, spacing):
"""Set inter-letter spacing value via CSS style"""
text = f"letter-spacing: {spacing}"
self.append_styled_span(text)
return self
def set_lineheight(self, lineheight):
"""Set line height name via CSS style - block-level only."""
text = f"line-height: {lineheight}"
self.add_style(text)
return self
def set_margins(self, val):
"""Set margin values via CSS style"""
text = "margins: %s" % val
self.append_styled_span(text)
return self
def set_opacity(self, opacity):
"""Set opacity via CSS style"""
text = f"opacity: {opacity}"
self.append_styled_span(text)
return self
def set_pagebreak_after(self):
"""Insert a page break after this node."""
text = "page-break-after: always"
self.add_style(text)
return self
def set_pagebreak_before(self):
"""Insert a page break before this node."""
text = "page-break-before: always"
self.add_style(text)
return self
def set_properties(
self,
align=None,
bgcolor=None,
bold=None,
color=None,
columns=None,
font=None,
fontsize=None,
indent=None,
italic=None,
leading=None,
letter_spacing=None,
lineheight=None,
margins=None,
pagebreak_after=None,
pagebreak_before=None,
word_spacing=None,
unqid=None,
cls=None,
):
"""Set any or all properties of a node.
To be used for existing nodes preferably.
"""
root = self.root
temp = root.add_division()
if align is not None:
temp.set_align(align)
if bgcolor is not None:
temp.set_bgcolor(bgcolor)
if bold is not None:
temp.set_bold(bold)
if color is not None:
temp.set_color(color)
if columns is not None:
temp.set_columns(columns)
if font is not None:
temp.set_font(font)
if fontsize is not None:
temp.set_fontsize(fontsize)
if indent is not None:
temp.set_text_indent(indent)
if italic is not None:
temp.set_italic(italic)
if leading is not None:
temp.set_leading(leading)
if letter_spacing is not None:
temp.set_letter_spacing(letter_spacing)
if lineheight is not None:
temp.set_lineheight(lineheight)
if margins is not None:
temp.set_margins(margins)
if pagebreak_after is not None:
temp.set_pagebreak_after()
if pagebreak_before is not None:
temp.set_pagebreak_before()
if word_spacing is not None:
temp.set_word_spacing(word_spacing)
if unqid is not None:
self.set_id(unqid)
if cls is not None:
self.add_class(cls)
styles = []
top_style = temp.get_attribute_value("style")
if top_style is not None:
styles.append(top_style)
child = temp.first_child
while child:
styles.append(child.get_attribute_value("style"))
child = child.first_child
self.set_attribute("style", ";".join(styles))
temp.remove()
return self
def set_text_indent(self, indent):
"""Set text indentation name via CSS style - block-level only."""
text = f"text-indent: {indent}"
self.add_style(text)
return self
def set_underline(self, val="underline"):
text = "text-decoration: %s" % val
self.append_styled_span(text)
return self
def set_word_spacing(self, spacing):
"""Set inter-word spacing value via CSS style"""
text = f"word-spacing: {spacing}"
self.append_styled_span(text)
return self
def span_bottom(self):
"""Find deepest level in stacked spans."""
parent = self
child = self.last_child
if child is None:
return None
while child.is_text:
child = child.previous
if child is None:
break
if child is None or child.tagname != "span":
return None
while True:
if child is None:
return parent
if child.tagname in ("a", "sub","sup","body") or child.is_text:
child = child.next
continue
if child.tagname == "span":
parent = child
child = child.first_child
else:
return parent
@property
def tagname( self):
return mupdf.fz_xml_tag( self.this)
@property
def text( self):
return mupdf.fz_xml_text( self.this)
add_var = add_code
add_samp = add_code
add_kbd = add_code
class Colorspace:
def __init__(self, type_):
"""Supported are GRAY, RGB and CMYK."""
if isinstance( type_, mupdf.FzColorspace):
self.this = type_
elif type_ == CS_GRAY:
self.this = mupdf.FzColorspace(mupdf.FzColorspace.Fixed_GRAY)
elif type_ == CS_CMYK:
self.this = mupdf.FzColorspace(mupdf.FzColorspace.Fixed_CMYK)
elif type_ == CS_RGB:
self.this = mupdf.FzColorspace(mupdf.FzColorspace.Fixed_RGB)
else:
self.this = mupdf.FzColorspace(mupdf.FzColorspace.Fixed_RGB)
def __repr__(self):
x = ("", "GRAY", "", "RGB", "CMYK")[self.n]
return "Colorspace(CS_%s) - %s" % (x, self.name)
def _name(self):
return mupdf.fz_colorspace_name(self.this)
@property
def n(self):
"""Size of one pixel."""
return mupdf.fz_colorspace_n(self.this)
@property
def name(self):
"""Name of the Colorspace."""
return self._name()
class DeviceWrapper:
def __init__(self, *args):
if args_match( args, mupdf.FzDevice):
device, = args
self.this = device
elif args_match( args, Pixmap, None):
pm, clip = args
bbox = JM_irect_from_py( clip)
if mupdf.fz_is_infinite_irect( bbox):
self.this = mupdf.fz_new_draw_device( mupdf.FzMatrix(), pm)
else:
self.this = mupdf.fz_new_draw_device_with_bbox( mupdf.FzMatrix(), pm, bbox)
elif args_match( args, mupdf.FzDisplayList):
dl, = args
self.this = mupdf.fz_new_list_device( dl)
elif args_match( args, mupdf.FzStextPage, None):
tp, flags = args
opts = mupdf.FzStextOptions( flags)
self.this = mupdf.fz_new_stext_device( tp, opts)
else:
raise Exception( f'Unrecognised args for DeviceWrapper: {args!r}')
class DisplayList:
def __del__(self):
if not type(self) is DisplayList: return
self.thisown = False
def __init__(self, *args):
if len(args) == 1 and isinstance(args[0], mupdf.FzRect):
self.this = mupdf.FzDisplayList(args[0])
elif len(args) == 1 and isinstance(args[0], mupdf.FzDisplayList):
self.this = args[0]
else:
assert 0, f'Unrecognised {args=}'
def get_pixmap(self, matrix=None, colorspace=None, alpha=0, clip=None):
if isinstance(colorspace, Colorspace):
colorspace = colorspace.this
else:
colorspace = mupdf.FzColorspace(mupdf.FzColorspace.Fixed_RGB)
val = JM_pixmap_from_display_list(self.this, matrix, colorspace, alpha, clip, None)
val.thisown = True
return val
def get_textpage(self, flags=3):
"""Make a TextPage from a DisplayList."""
stext_options = mupdf.FzStextOptions()
stext_options.flags = flags
val = mupdf.FzStextPage(self.this, stext_options)
val.thisown = True
return val
@property
def rect(self):
val = JM_py_from_rect(mupdf.fz_bound_display_list(self.this))
val = Rect(val)
return val
def run(self, dw, m, area):
mupdf.fz_run_display_list(
self.this,
dw.device,
JM_matrix_from_py(m),
JM_rect_from_py(area),
mupdf.FzCookie(),
)
if g_use_extra:
extra_FzDocument_insert_pdf = extra.FzDocument_insert_pdf
class Document:
def __contains__(self, loc) -> bool:
if type(loc) is int:
if loc < self.page_count:
return True
return False
if type(loc) not in (tuple, list) or len(loc) != 2:
return False
chapter, pno = loc
if (0
or not isinstance(chapter, int)
or chapter < 0
or chapter >= self.chapter_count
):
return False
if (0
or not isinstance(pno, int)
or pno < 0
or pno >= self.chapter_page_count(chapter)
):
return False
return True
def __delitem__(self, i)->None:
if not self.is_pdf:
raise ValueError("is no PDF")
if type(i) is int:
return self.delete_page(i)
if type(i) in (list, tuple, range):
return self.delete_pages(i)
if type(i) is not slice:
raise ValueError("bad argument type")
pc = self.page_count
start = i.start if i.start else 0
stop = i.stop if i.stop else pc
step = i.step if i.step else 1
while start < 0:
start += pc
if start >= pc:
raise ValueError("bad page number(s)")
while stop < 0:
stop += pc
if stop > pc:
raise ValueError("bad page number(s)")
return self.delete_pages(range(start, stop, step))
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
@typing.overload
def __getitem__(self, i: int = 0) -> Page:
...
if sys.version_info >= (3, 9):
@typing.overload
def __getitem__(self, i: slice) -> list[Page]:
...
@typing.overload
def __getitem__(self, i: tuple[int, int]) -> Page:
...
def __getitem__(self, i=0):
if isinstance(i, slice):
return [self[j] for j in range(*i.indices(len(self)))]
assert isinstance(i, int) or (isinstance(i, tuple) and len(i) == 2 and all(isinstance(x, int) for x in i)), \
f'Invalid item number: {i=}.'
if i not in self:
raise IndexError(f"page {i} not in document")
return self.load_page(i)
def __init__(self, filename=None, stream=None, filetype=None, rect=None, width=0, height=0, fontsize=11):
"""Creates a document. Use 'open' as a synonym.
Notes:
Basic usages:
open() - new PDF document
open(filename) - string or pathlib.Path, must have supported
file extension.
open(type, buffer) - type: valid extension, buffer: bytes object.
open(stream=buffer, filetype=type) - keyword version of previous.
open(filename, fileype=type) - filename with unrecognized extension.
rect, width, height, fontsize: layout reflowable document
on open (e.g. EPUB). Ignored if n/a.
"""
# We temporarily set JM_mupdf_show_errors=0 while we are constructing,
# then restore its original value in a `finally:` block.
#
global JM_mupdf_show_errors
JM_mupdf_show_errors_old = JM_mupdf_show_errors
JM_mupdf_show_errors = 0
try:
self.is_closed = False
self.is_encrypted = False
self.is_encrypted = False
self.metadata = None
self.FontInfos = []
self.Graftmaps = {}
self.ShownPages = {}
self.InsertedImages = {}
self._page_refs = weakref.WeakValueDictionary()
if isinstance(filename, mupdf.PdfDocument):
pdf_document = filename
self.this = pdf_document
self.this_is_pdf = True
return
# Classic implementation temporarily sets JM_mupdf_show_errors=0 then
# restores the previous value in `fz_always() {...}` before returning.
#
if not filename or type(filename) is str:
pass
elif hasattr(filename, "absolute"):
filename = str(filename)
elif hasattr(filename, "name"):
filename = filename.name
else:
raise TypeError(f"bad filename: {type(filename)=} {filename=}.")
if stream is not None:
if type(stream) is bytes:
self.stream = stream
elif type(stream) is bytearray:
self.stream = bytes(stream)
elif type(stream) is io.BytesIO:
self.stream = stream.getvalue()
else:
raise TypeError(f"bad stream: {type(stream)=}.")
stream = self.stream
if not (filename or filetype):
filename = 'pdf'
else:
self.stream = None
if filename and self.stream is None:
from_file = True
self._name = filename
else:
from_file = False
self._name = ""
if from_file:
if not os.path.exists(filename):
msg = f"no such file: '{filename}'"
raise FileNotFoundError(msg)
elif not os.path.isfile(filename):
msg = f"'{filename}' is no file"
raise FileDataError(msg)
if from_file and os.path.getsize(filename) == 0:
raise EmptyFileError(f'Cannot open empty file: {filename=}.')
if type(self.stream) is bytes and len(self.stream) == 0:
raise EmptyFileError(f'Cannot open empty stream.')
w = width
h = height
r = JM_rect_from_py(rect)
if not mupdf.fz_is_infinite_rect(r):
w = r.x1 - r.x0
h = r.y1 - r.y0
if stream: # stream given, **MUST** be bytes!
assert isinstance(stream, bytes)
c = stream
#len = (size_t) PyBytes_Size(stream);
if mupdf_cppyy:
buffer_ = mupdf.fz_new_buffer_from_copied_data( c)
data = mupdf.fz_open_buffer( buffer_)
else:
# Pass raw bytes data to mupdf.fz_open_memory(). This assumes
# that the bytes string will not be modified; i think the
# original PyMuPDF code makes the same assumption. Presumably
# setting self.stream above ensures that the bytes will not be
# garbage collected?
data = mupdf.fz_open_memory(mupdf.python_buffer_data(c), len(c))
magic = filename
if not magic:
magic = filetype
# fixme: pymupdf does:
# handler = fz_recognize_document(gctx, filetype);
# if (!handler) raise ValueError( MSG_BAD_FILETYPE)
# but prefer to leave fz_open_document_with_stream() to raise.
try:
doc = mupdf.fz_open_document_with_stream(magic, data)
except Exception as e:
if g_exceptions_verbose > 1: exception_info()
raise FileDataError(f'Failed to open stream') from e
else:
if filename:
if not filetype:
try:
doc = mupdf.fz_open_document(filename)
except Exception as e:
if g_exceptions_verbose > 1: exception_info()
raise FileDataError(f'Failed to open file {filename!r}.') from e
else:
handler = mupdf.ll_fz_recognize_document(filetype)
if handler:
if handler.open:
#log( f'{handler.open=}')
#log( f'{dir(handler.open)=}')
try:
if mupdf_version_tuple >= (1, 24):
stream = mupdf.FzStream(filename)
accel = mupdf.FzStream()
archive = mupdf.FzArchive(None)
if mupdf_version_tuple >= (1, 24, 8):
doc = mupdf.ll_fz_document_handler_open(
handler,
stream.m_internal,
accel.m_internal,
archive.m_internal,
None, # recognize_state
)
else:
doc = mupdf.ll_fz_document_open_fn_call(
handler.open,
stream.m_internal,
accel.m_internal,
archive.m_internal,
)
else:
doc = mupdf.ll_fz_document_open_fn_call( handler.open, filename)
except Exception as e:
if g_exceptions_verbose > 1: exception_info()
raise FileDataError(f'Failed to open file {filename!r} as type {filetype!r}.') from e
doc = mupdf.FzDocument( doc)
else:
if mupdf_version_tuple < (1, 24):
if handler.open_with_stream:
data = mupdf.fz_open_file( filename)
doc = mupdf.fz_document_open_with_stream_fn_call( handler.open_with_stream, data)
else:
assert 0
else:
raise ValueError( MSG_BAD_FILETYPE)
else:
pdf = mupdf.PdfDocument()
doc = mupdf.FzDocument(pdf)
if w > 0 and h > 0:
mupdf.fz_layout_document(doc, w, h, fontsize)
elif mupdf.fz_is_document_reflowable(doc):
mupdf.fz_layout_document(doc, 400, 600, 11)
this = doc
self.this = this
# fixme: not sure where self.thisown gets initialised in PyMuPDF.
#
self.thisown = True
if self.thisown:
self._graft_id = TOOLS.gen_id()
if self.needs_pass:
self.is_encrypted = True
else: # we won't init until doc is decrypted
self.init_doc()
# the following hack detects invalid/empty SVG files, which else may lead
# to interpreter crashes
if filename and filename.lower().endswith("svg") or filetype and "svg" in filetype.lower():
try:
_ = self.convert_to_pdf() # this seems to always work
except Exception as e:
if g_exceptions_verbose > 1: exception_info()
raise FileDataError("cannot open broken document") from e
if g_use_extra:
self.this_is_pdf = isinstance( self.this, mupdf.PdfDocument)
if self.this_is_pdf:
self.page_count2 = extra.page_count_pdf
else:
self.page_count2 = extra.page_count_fz
finally:
JM_mupdf_show_errors = JM_mupdf_show_errors_old
def __len__(self) -> int:
return self.page_count
def __repr__(self) -> str:
m = "closed " if self.is_closed else ""
if self.stream is None:
if self.name == "":
return m + "Document(<new PDF, doc# %i>)" % self._graft_id
return m + "Document('%s')" % (self.name,)
return m + "Document('%s', <memory, doc# %i>)" % (self.name, self._graft_id)
def _addFormFont(self, name, font):
"""Add new form font."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return
fonts = mupdf.pdf_dict_getl(
mupdf.pdf_trailer( pdf),
PDF_NAME('Root'),
PDF_NAME('AcroForm'),
PDF_NAME('DR'),
PDF_NAME('Font'),
)
if not fonts.m_internal or not mupdf.pdf_is_dict( fonts):
raise RuntimeError( "PDF has no form fonts yet")
k = mupdf.pdf_new_name( name)
v = JM_pdf_obj_from_str( pdf, font)
mupdf.pdf_dict_put( fonts, k, v)
def _delToC(self):
"""Delete the TOC."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
xrefs = [] # create Python list
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return xrefs # not a pdf
# get the main root
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
# get the outline root
olroot = mupdf.pdf_dict_get(root, PDF_NAME('Outlines'))
if not olroot.m_internal:
return xrefs # no outlines or some problem
first = mupdf.pdf_dict_get(olroot, PDF_NAME('First')) # first outline
xrefs = JM_outline_xrefs(first, xrefs)
xref_count = len(xrefs)
olroot_xref = mupdf.pdf_to_num(olroot) # delete OL root
mupdf.pdf_delete_object(pdf, olroot_xref) # delete OL root
mupdf.pdf_dict_del(root, PDF_NAME('Outlines')) # delete OL root
for i in range(xref_count):
_, xref = JM_INT_ITEM(xrefs, i)
mupdf.pdf_delete_object(pdf, xref) # delete outline item
xrefs.append(olroot_xref)
val = xrefs
self.init_doc()
return val
def _delete_page(self, pno):
pdf = _as_pdf_document(self)
mupdf.pdf_delete_page( pdf, pno)
if pdf.m_internal.rev_page_map:
mupdf.ll_pdf_drop_page_tree( pdf.m_internal)
def _deleteObject(self, xref):
"""Delete object."""
pdf = _as_pdf_document(self)
if not _INRANGE(xref, 1, mupdf.pdf_xref_len(pdf)-1):
raise ValueError( MSG_BAD_XREF)
mupdf.pdf_delete_object(pdf, xref)
def _embeddedFileGet(self, idx):
pdf = _as_pdf_document(self)
names = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
entry = mupdf.pdf_array_get(names, 2*idx+1)
filespec = mupdf.pdf_dict_getl(entry, PDF_NAME('EF'), PDF_NAME('F'))
buf = mupdf.pdf_load_stream(filespec)
cont = JM_BinFromBuffer(buf)
return cont
def _embeddedFileIndex(self, item: typing.Union[int, str]) -> int:
filenames = self.embfile_names()
msg = "'%s' not in EmbeddedFiles array." % str(item)
if item in filenames:
idx = filenames.index(item)
elif item in range(len(filenames)):
idx = item
else:
raise ValueError(msg)
return idx
def _embfile_add(self, name, buffer_, filename=None, ufilename=None, desc=None):
pdf = _as_pdf_document(self)
data = JM_BufferFromBytes(buffer_)
if not data.m_internal:
raise TypeError( MSG_BAD_BUFFER)
names = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
if not mupdf.pdf_is_array(names):
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
names = mupdf.pdf_new_array(pdf, 6) # an even number!
mupdf.pdf_dict_putl(
root,
names,
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
fileentry = JM_embed_file(pdf, data, filename, ufilename, desc, 1)
xref = mupdf.pdf_to_num(
mupdf.pdf_dict_getl(fileentry, PDF_NAME('EF'), PDF_NAME('F'))
)
mupdf.pdf_array_push(names, mupdf.pdf_new_text_string(name))
mupdf.pdf_array_push(names, fileentry)
return xref
def _embfile_del(self, idx):
pdf = _as_pdf_document(self)
names = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
mupdf.pdf_array_delete(names, idx + 1)
mupdf.pdf_array_delete(names, idx)
def _embfile_info(self, idx, infodict):
pdf = _as_pdf_document(self)
xref = 0
ci_xref=0
trailer = mupdf.pdf_trailer(pdf)
names = mupdf.pdf_dict_getl(
trailer,
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
o = mupdf.pdf_array_get(names, 2*idx+1)
ci = mupdf.pdf_dict_get(o, PDF_NAME('CI'))
if ci.m_internal:
ci_xref = mupdf.pdf_to_num(ci)
infodict["collection"] = ci_xref
name = mupdf.pdf_to_text_string(mupdf.pdf_dict_get(o, PDF_NAME('F')))
infodict[dictkey_filename] = JM_EscapeStrFromStr(name)
name = mupdf.pdf_to_text_string(mupdf.pdf_dict_get(o, PDF_NAME('UF')))
infodict[dictkey_ufilename] = JM_EscapeStrFromStr(name)
name = mupdf.pdf_to_text_string(mupdf.pdf_dict_get(o, PDF_NAME('Desc')))
infodict[dictkey_desc] = JM_UnicodeFromStr(name)
len_ = -1
DL = -1
fileentry = mupdf.pdf_dict_getl(o, PDF_NAME('EF'), PDF_NAME('F'))
xref = mupdf.pdf_to_num(fileentry)
o = mupdf.pdf_dict_get(fileentry, PDF_NAME('Length'))
if o.m_internal:
len_ = mupdf.pdf_to_int(o)
o = mupdf.pdf_dict_get(fileentry, PDF_NAME('DL'))
if o.m_internal:
DL = mupdf.pdf_to_int(o)
else:
o = mupdf.pdf_dict_getl(fileentry, PDF_NAME('Params'), PDF_NAME('Size'))
if o.m_internal:
DL = mupdf.pdf_to_int(o)
infodict[dictkey_size] = DL
infodict[dictkey_length] = len_
return xref
def _embfile_names(self, namelist):
"""Get list of embedded file names."""
pdf = _as_pdf_document(self)
names = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
if mupdf.pdf_is_array(names):
n = mupdf.pdf_array_len(names)
for i in range(0, n, 2):
val = JM_EscapeStrFromStr(
mupdf.pdf_to_text_string(
mupdf.pdf_array_get(names, i)
)
)
namelist.append(val)
def _embfile_upd(self, idx, buffer_=None, filename=None, ufilename=None, desc=None):
pdf = _as_pdf_document(self)
xref = 0
names = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
entry = mupdf.pdf_array_get(names, 2*idx+1)
filespec = mupdf.pdf_dict_getl(entry, PDF_NAME('EF'), PDF_NAME('F'))
if not filespec.m_internal:
RAISEPY( "bad PDF: no /EF object", JM_Exc_FileDataError)
res = JM_BufferFromBytes(buffer_)
if buffer_ and buffer_.m_internal and not res.m_internal:
raise TypeError( MSG_BAD_BUFFER)
if res.m_internal and buffer_ and buffer_.m_internal:
JM_update_stream(pdf, filespec, res, 1)
# adjust /DL and /Size parameters
len, _ = mupdf.fz_buffer_storage(res)
l = mupdf.pdf_new_int(len)
mupdf.pdf_dict_put(filespec, PDF_NAME('DL'), l)
mupdf.pdf_dict_putl(filespec, l, PDF_NAME('Params'), PDF_NAME('Size'))
xref = mupdf.pdf_to_num(filespec)
if filename:
mupdf.pdf_dict_put_text_string(entry, PDF_NAME('F'), filename)
if ufilename:
mupdf.pdf_dict_put_text_string(entry, PDF_NAME('UF'), ufilename)
if desc:
mupdf.pdf_dict_put_text_string(entry, PDF_NAME('Desc'), desc)
return xref
def _extend_toc_items(self, items):
"""Add color info to all items of an extended TOC list."""
if self.is_closed:
raise ValueError("document closed")
if g_use_extra:
return extra.Document_extend_toc_items( self.this, items)
pdf = _as_pdf_document(self)
zoom = "zoom"
bold = "bold"
italic = "italic"
collapse = "collapse"
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
if not root.m_internal:
return
olroot = mupdf.pdf_dict_get(root, PDF_NAME('Outlines'))
if not olroot.m_internal:
return
first = mupdf.pdf_dict_get(olroot, PDF_NAME('First'))
if not first.m_internal:
return
xrefs = []
xrefs = JM_outline_xrefs(first, xrefs)
n = len(xrefs)
m = len(items)
if not n:
return
if n != m:
raise IndexError( "internal error finding outline xrefs")
# update all TOC item dictionaries
for i in range(n):
xref = int(xrefs[i])
item = items[i]
itemdict = item[3]
if not isinstance(itemdict, dict):
raise ValueError( "need non-simple TOC format")
itemdict[dictkey_xref] = xrefs[i]
bm = mupdf.pdf_load_object(pdf, xref)
flags = mupdf.pdf_to_int( mupdf.pdf_dict_get(bm, PDF_NAME('F')))
if flags == 1:
itemdict[italic] = True
elif flags == 2:
itemdict[bold] = True
elif flags == 3:
itemdict[italic] = True
itemdict[bold] = True
count = mupdf.pdf_to_int( mupdf.pdf_dict_get(bm, PDF_NAME('Count')))
if count < 0:
itemdict[collapse] = True
elif count > 0:
itemdict[collapse] = False
col = mupdf.pdf_dict_get(bm, PDF_NAME('C'))
if mupdf.pdf_is_array(col) and mupdf.pdf_array_len(col) == 3:
color = (
mupdf.pdf_to_real(mupdf.pdf_array_get(col, 0)),
mupdf.pdf_to_real(mupdf.pdf_array_get(col, 1)),
mupdf.pdf_to_real(mupdf.pdf_array_get(col, 2)),
)
itemdict[dictkey_color] = color
z=0
obj = mupdf.pdf_dict_get(bm, PDF_NAME('Dest'))
if not obj.m_internal or not mupdf.pdf_is_array(obj):
obj = mupdf.pdf_dict_getl(bm, PDF_NAME('A'), PDF_NAME('D'))
if mupdf.pdf_is_array(obj) and mupdf.pdf_array_len(obj) == 5:
z = mupdf.pdf_to_real(mupdf.pdf_array_get(obj, 4))
itemdict[zoom] = float(z)
item[3] = itemdict
items[i] = item
def _forget_page(self, page: Page):
"""Remove a page from document page dict."""
pid = id(page)
if pid in self._page_refs:
#self._page_refs[pid] = None
del self._page_refs[pid]
def _get_char_widths(self, xref: int, bfname: str, ext: str, ordering: int, limit: int, idx: int = 0):
pdf = _as_pdf_document(self)
mylimit = limit
if mylimit < 256:
mylimit = 256
if ordering >= 0:
data, size, index = mupdf.fz_lookup_cjk_font(ordering)
font = mupdf.fz_new_font_from_memory(None, data, size, index, 0)
else:
data, size = mupdf.fz_lookup_base14_font(bfname)
if data:
font = mupdf.fz_new_font_from_memory(bfname, data, size, 0, 0)
else:
buf = JM_get_fontbuffer(pdf, xref)
if not buf.m_internal:
raise Exception("font at xref %d is not supported" % xref)
font = mupdf.fz_new_font_from_buffer(None, buf, idx, 0)
wlist = []
for i in range(mylimit):
glyph = mupdf.fz_encode_character(font, i)
adv = mupdf.fz_advance_glyph(font, glyph, 0)
if ordering >= 0:
glyph = i
if glyph > 0:
wlist.append( (glyph, adv))
else:
wlist.append( (glyph, 0.0))
return wlist
def _get_page_labels(self):
pdf = _as_pdf_document(self)
rc = []
pagelabels = mupdf.pdf_new_name("PageLabels")
obj = mupdf.pdf_dict_getl( mupdf.pdf_trailer(pdf), PDF_NAME('Root'), pagelabels)
if not obj.m_internal:
return rc
# simple case: direct /Nums object
nums = mupdf.pdf_resolve_indirect( mupdf.pdf_dict_get( obj, PDF_NAME('Nums')))
if nums.m_internal:
JM_get_page_labels(rc, nums)
return rc
# case: /Kids/Nums
nums = mupdf.pdf_resolve_indirect( mupdf.pdf_dict_getl(obj, PDF_NAME('Kids'), PDF_NAME('Nums')))
if nums.m_internal:
JM_get_page_labels(rc, nums)
return rc
# case: /Kids is an array of multiple /Nums
kids = mupdf.pdf_resolve_indirect( mupdf.pdf_dict_get( obj, PDF_NAME('Kids')))
if not kids.m_internal or not mupdf.pdf_is_array(kids):
return rc
n = mupdf.pdf_array_len(kids)
for i in range(n):
nums = mupdf.pdf_resolve_indirect(
mupdf.pdf_dict_get( mupdf.pdf_array_get(kids, i)),
PDF_NAME('Nums'),
)
JM_get_page_labels(rc, nums)
return rc
def _getMetadata(self, key):
"""Get metadata."""
try:
return mupdf.fz_lookup_metadata2( self.this, key)
except Exception:
if g_exceptions_verbose > 2: exception_info()
return ''
def _getOLRootNumber(self):
"""Get xref of Outline Root, create it if missing."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
# get main root
root = mupdf.pdf_dict_get( mupdf.pdf_trailer( pdf), PDF_NAME('Root'))
# get outline root
olroot = mupdf.pdf_dict_get( root, PDF_NAME('Outlines'))
if not olroot.m_internal:
olroot = mupdf.pdf_new_dict( pdf, 4)
mupdf.pdf_dict_put( olroot, PDF_NAME('Type'), PDF_NAME('Outlines'))
ind_obj = mupdf.pdf_add_object( pdf, olroot)
mupdf.pdf_dict_put( root, PDF_NAME('Outlines'), ind_obj)
olroot = mupdf.pdf_dict_get( root, PDF_NAME('Outlines'))
return mupdf.pdf_to_num( olroot)
def _getPDFfileid(self):
"""Get PDF file id."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return
idlist = []
identity = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('ID'))
if identity.m_internal:
n = mupdf.pdf_array_len(identity)
for i in range(n):
o = mupdf.pdf_array_get(identity, i)
text = mupdf.pdf_to_text_string(o)
hex_ = binascii.hexlify(text)
idlist.append(hex_)
return idlist
def _getPageInfo(self, pno, what):
"""List fonts, images, XObjects used on a page."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
doc = self.this
pageCount = mupdf.pdf_count_pages(doc) if isinstance(doc, mupdf.PdfDocument) else mupdf.fz_count_pages(doc)
n = pno # pno < 0 is allowed
while n < 0:
n += pageCount # make it non-negative
if n >= pageCount:
raise ValueError( MSG_BAD_PAGENO)
pdf = _as_pdf_document(self)
pageref = mupdf.pdf_lookup_page_obj(pdf, n)
rsrc = mupdf.pdf_dict_get_inheritable(pageref, mupdf.PDF_ENUM_NAME_Resources)
liste = []
tracer = []
if rsrc.m_internal:
JM_scan_resources(pdf, rsrc, liste, what, 0, tracer)
return liste
def _insert_font(self, fontfile=None, fontbuffer=None):
'''
Utility: insert font from file or binary.
'''
pdf = _as_pdf_document(self)
if not fontfile and not fontbuffer:
raise ValueError( MSG_FILE_OR_BUFFER)
value = JM_insert_font(pdf, None, fontfile, fontbuffer, 0, 0, 0, 0, 0, -1)
return value
def _loadOutline(self):
"""Load first outline."""
doc = self.this
assert isinstance( doc, mupdf.FzDocument)
try:
ol = mupdf.fz_load_outline( doc)
except Exception:
if g_exceptions_verbose > 1: exception_info()
return
return Outline( ol)
def _make_page_map(self):
"""Make an array page number -> page object."""
if self.is_closed:
raise ValueError("document closed")
assert 0, f'_make_page_map() is no-op'
def _move_copy_page(self, pno, nb, before, copy):
"""Move or copy a PDF page reference."""
pdf = _as_pdf_document(self)
same = 0
# get the two page objects -----------------------------------
# locate the /Kids arrays and indices in each
page1, parent1, i1 = pdf_lookup_page_loc( pdf, pno)
kids1 = mupdf.pdf_dict_get( parent1, PDF_NAME('Kids'))
page2, parent2, i2 = pdf_lookup_page_loc( pdf, nb)
kids2 = mupdf.pdf_dict_get( parent2, PDF_NAME('Kids'))
if before: # calc index of source page in target /Kids
pos = i2
else:
pos = i2 + 1
# same /Kids array? ------------------------------------------
same = mupdf.pdf_objcmp( kids1, kids2)
# put source page in target /Kids array ----------------------
if not copy and same != 0: # update parent in page object
mupdf.pdf_dict_put( page1, PDF_NAME('Parent'), parent2)
mupdf.pdf_array_insert( kids2, page1, pos)
if same != 0: # different /Kids arrays ----------------------
parent = parent2
while parent.m_internal: # increase /Count objects in parents
count = mupdf.pdf_dict_get_int( parent, PDF_NAME('Count'))
mupdf.pdf_dict_put_int( parent, PDF_NAME('Count'), count + 1)
parent = mupdf.pdf_dict_get( parent, PDF_NAME('Parent'))
if not copy: # delete original item
mupdf.pdf_array_delete( kids1, i1)
parent = parent1
while parent.m_internal: # decrease /Count objects in parents
count = mupdf.pdf_dict_get_int( parent, PDF_NAME('Count'))
mupdf.pdf_dict_put_int( parent, PDF_NAME('Count'), count - 1)
parent = mupdf.pdf_dict_get( parent, PDF_NAME('Parent'))
else: # same /Kids array
if copy: # source page is copied
parent = parent2
while parent.m_internal: # increase /Count object in parents
count = mupdf.pdf_dict_get_int( parent, PDF_NAME('Count'))
mupdf.pdf_dict_put_int( parent, PDF_NAME('Count'), count + 1)
parent = mupdf.pdf_dict_get( parent, PDF_NAME('Parent'))
else:
if i1 < pos:
mupdf.pdf_array_delete( kids1, i1)
else:
mupdf.pdf_array_delete( kids1, i1 + 1)
if pdf.m_internal.rev_page_map: # page map no longer valid: drop it
mupdf.ll_pdf_drop_page_tree( pdf.m_internal)
self._reset_page_refs()
def _newPage(self, pno=-1, width=595, height=842):
"""Make a new PDF page."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if g_use_extra:
extra._newPage( self.this, pno, width, height)
else:
pdf = _as_pdf_document(self)
mediabox = mupdf.FzRect(mupdf.FzRect.Fixed_UNIT)
mediabox.x1 = width
mediabox.y1 = height
contents = mupdf.FzBuffer()
if pno < -1:
raise ValueError( MSG_BAD_PAGENO)
# create /Resources and /Contents objects
#resources = pdf.add_object(pdf.new_dict(1))
resources = mupdf.pdf_add_new_dict(pdf, 1)
page_obj = mupdf.pdf_add_page( pdf, mediabox, 0, resources, contents)
mupdf.pdf_insert_page( pdf, pno, page_obj)
# fixme: pdf->dirty = 1;
self._reset_page_refs()
return self[pno]
def _remove_links_to(self, numbers):
pdf = _as_pdf_document(self)
_remove_dest_range(pdf, numbers)
def _remove_toc_item(self, xref):
# "remove" bookmark by letting it point to nowhere
pdf = _as_pdf_document(self)
item = mupdf.pdf_new_indirect(pdf, xref, 0)
mupdf.pdf_dict_del( item, PDF_NAME('Dest'))
mupdf.pdf_dict_del( item, PDF_NAME('A'))
color = mupdf.pdf_new_array( pdf, 3)
for i in range(3):
mupdf.pdf_array_push_real( color, 0.8)
mupdf.pdf_dict_put( item, PDF_NAME('C'), color)
def _reset_page_refs(self):
"""Invalidate all pages in document dictionary."""
if getattr(self, "is_closed", True):
return
pages = [p for p in self._page_refs.values()]
for page in pages:
if page:
page._erase()
page = None
self._page_refs.clear()
def _set_page_labels(self, labels):
pdf = _as_pdf_document(self)
pagelabels = mupdf.pdf_new_name("PageLabels")
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
mupdf.pdf_dict_del(root, pagelabels)
mupdf.pdf_dict_putl(root, mupdf.pdf_new_array(pdf, 0), pagelabels, PDF_NAME('Nums'))
xref = self.pdf_catalog()
text = self.xref_object(xref, compressed=True)
text = text.replace("/Nums[]", "/Nums[%s]" % labels)
self.update_object(xref, text)
def _update_toc_item(self, xref, action=None, title=None, flags=0, collapse=None, color=None):
'''
"update" bookmark by letting it point to nowhere
'''
pdf = _as_pdf_document(self)
item = mupdf.pdf_new_indirect( pdf, xref, 0)
if title:
mupdf.pdf_dict_put_text_string( item, PDF_NAME('Title'), title)
if action:
mupdf.pdf_dict_del( item, PDF_NAME('Dest'))
obj = JM_pdf_obj_from_str( pdf, action)
mupdf.pdf_dict_put( item, PDF_NAME('A'), obj)
mupdf.pdf_dict_put_int( item, PDF_NAME('F'), flags)
if color:
c = mupdf.pdf_new_array( pdf, 3)
for i in range(3):
f = color[i]
mupdf.pdf_array_push_real( c, f)
mupdf.pdf_dict_put( item, PDF_NAME('C'), c)
elif color is not None:
mupdf.pdf_dict_del( item, PDF_NAME('C'))
if collapse is not None:
if mupdf.pdf_dict_get( item, PDF_NAME('Count')).m_internal:
i = mupdf.pdf_dict_get_int( item, PDF_NAME('Count'))
if (i < 0 and collapse is False) or (i > 0 and collapse is True):
i = i * (-1)
mupdf.pdf_dict_put_int( item, PDF_NAME('Count'), i)
@property
def FormFonts(self):
"""Get list of field font resource names."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return
fonts = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('AcroForm'),
PDF_NAME('DR'),
PDF_NAME('Font'),
)
liste = list()
if fonts.m_internal and mupdf.pdf_is_dict(fonts): # fonts exist
n = mupdf.pdf_dict_len(fonts)
for i in range(n):
f = mupdf.pdf_dict_get_key(fonts, i)
liste.append(JM_UnicodeFromStr(mupdf.pdf_to_name(f)))
return liste
def add_layer(self, name, creator=None, on=None):
"""Add a new OC layer."""
pdf = _as_pdf_document(self)
JM_add_layer_config( pdf, name, creator, on)
mupdf.ll_pdf_read_ocg( pdf.m_internal)
def add_ocg(self, name, config=-1, on=1, intent=None, usage=None):
"""Add new optional content group."""
xref = 0
pdf = _as_pdf_document(self)
# make the OCG
ocg = mupdf.pdf_add_new_dict(pdf, 3)
mupdf.pdf_dict_put(ocg, PDF_NAME('Type'), PDF_NAME('OCG'))
mupdf.pdf_dict_put_text_string(ocg, PDF_NAME('Name'), name)
intents = mupdf.pdf_dict_put_array(ocg, PDF_NAME('Intent'), 2)
if not intent:
mupdf.pdf_array_push(intents, PDF_NAME('View'))
elif not isinstance(intent, str):
assert 0, f'fixme: intent is not a str. {type(intent)=} {type=}'
#n = len(intent)
#for i in range(n):
# item = intent[i]
# c = JM_StrAsChar(item);
# if (c) {
# pdf_array_push(gctx, intents, pdf_new_name(gctx, c));
# }
# Py_DECREF(item);
#}
else:
mupdf.pdf_array_push(intents, mupdf.pdf_new_name(intent))
use_for = mupdf.pdf_dict_put_dict(ocg, PDF_NAME('Usage'), 3)
ci_name = mupdf.pdf_new_name("CreatorInfo")
cre_info = mupdf.pdf_dict_put_dict(use_for, ci_name, 2)
mupdf.pdf_dict_put_text_string(cre_info, PDF_NAME('Creator'), "PyMuPDF")
if usage:
mupdf.pdf_dict_put_name(cre_info, PDF_NAME('Subtype'), usage)
else:
mupdf.pdf_dict_put_name(cre_info, PDF_NAME('Subtype'), "Artwork")
indocg = mupdf.pdf_add_object(pdf, ocg)
# Insert OCG in the right config
ocp = JM_ensure_ocproperties(pdf)
obj = mupdf.pdf_dict_get(ocp, PDF_NAME('OCGs'))
mupdf.pdf_array_push(obj, indocg)
if config > -1:
obj = mupdf.pdf_dict_get(ocp, PDF_NAME('Configs'))
if not mupdf.pdf_is_array(obj):
raise ValueError( MSG_BAD_OC_CONFIG)
cfg = mupdf.pdf_array_get(obj, config)
if not cfg.m_internal:
raise ValueError( MSG_BAD_OC_CONFIG)
else:
cfg = mupdf.pdf_dict_get(ocp, PDF_NAME('D'))
obj = mupdf.pdf_dict_get(cfg, PDF_NAME('Order'))
if not obj.m_internal:
obj = mupdf.pdf_dict_put_array(cfg, PDF_NAME('Order'), 1)
mupdf.pdf_array_push(obj, indocg)
if on:
obj = mupdf.pdf_dict_get(cfg, PDF_NAME('ON'))
if not obj.m_internal:
obj = mupdf.pdf_dict_put_array(cfg, PDF_NAME('ON'), 1)
else:
obj =mupdf.pdf_dict_get(cfg, PDF_NAME('OFF'))
if not obj.m_internal:
obj =mupdf.pdf_dict_put_array(cfg, PDF_NAME('OFF'), 1)
mupdf.pdf_array_push(obj, indocg)
# let MuPDF take note: re-read OCProperties
mupdf.ll_pdf_read_ocg(pdf.m_internal)
xref = mupdf.pdf_to_num(indocg)
return xref
def authenticate(self, password):
"""Decrypt document."""
if self.is_closed:
raise ValueError("document closed")
val = mupdf.fz_authenticate_password(self.this, password)
if val: # the doc is decrypted successfully and we init the outline
self.is_encrypted = False
self.is_encrypted = False
self.init_doc()
self.thisown = True
return val
def can_save_incrementally(self):
"""Check whether incremental saves are possible."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return False
return mupdf.pdf_can_be_saved_incrementally(pdf)
def bake(self, *, annots: bool = True, widgets: bool = True) -> None:
"""Convert annotations or fields to permanent content.
Notes:
Converts annotations or widgets to permanent page content, like
text and vector graphics, as appropriate.
After execution, pages will still look the same, but no longer
have annotations, respectively no fields.
If widgets are selected the PDF will no longer be a Form PDF.
Args:
annots: convert annotations
widgets: convert form fields
"""
pdf = _as_pdf_document(self)
mupdf.pdf_bake_document(pdf, int(annots), int(widgets))
@property
def chapter_count(self):
"""Number of chapters."""
if self.is_closed:
raise ValueError("document closed")
return mupdf.fz_count_chapters( self.this)
def chapter_page_count(self, chapter):
"""Page count of chapter."""
if self.is_closed:
raise ValueError("document closed")
chapters = mupdf.fz_count_chapters( self.this)
if chapter < 0 or chapter >= chapters:
raise ValueError( "bad chapter number")
pages = mupdf.fz_count_chapter_pages( self.this, chapter)
return pages
def close(self):
"""Close document."""
if getattr(self, "is_closed", True):
raise ValueError("document closed")
# self._cleanup()
if hasattr(self, "_outline") and self._outline:
self._outline = None
self._reset_page_refs()
#self.metadata = None
#self.stream = None
self.is_closed = True
#self.FontInfos = []
self.Graftmaps = {} # Fixes test_3140().
#self.ShownPages = {}
#self.InsertedImages = {}
#self.this = None
self.this = None
def convert_to_pdf(self, from_page=0, to_page=-1, rotate=0):
"""Convert document to a PDF, selecting page range and optional rotation. Output bytes object."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
fz_doc = self.this
fp = from_page
tp = to_page
srcCount = mupdf.fz_count_pages(fz_doc)
if fp < 0:
fp = 0
if fp > srcCount - 1:
fp = srcCount - 1
if tp < 0:
tp = srcCount - 1
if tp > srcCount - 1:
tp = srcCount - 1
len0 = len(JM_mupdf_warnings_store)
doc = JM_convert_to_pdf(fz_doc, fp, tp, rotate)
len1 = len(JM_mupdf_warnings_store)
for i in range(len0, len1):
message(f'{JM_mupdf_warnings_store[i]}')
return doc
def copy_page(self, pno: int, to: int =-1):
"""Copy a page within a PDF document.
This will only create another reference of the same page object.
Args:
pno: source page number
to: put before this page, '-1' means after last page.
"""
if self.is_closed:
raise ValueError("document closed")
page_count = len(self)
if (
pno not in range(page_count)
or to not in range(-1, page_count)
):
raise ValueError("bad page number(s)")
before = 1
copy = 1
if to == -1:
to = page_count - 1
before = 0
return self._move_copy_page(pno, to, before, copy)
def del_xml_metadata(self):
"""Delete XML metadata."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
root = mupdf.pdf_dict_get( mupdf.pdf_trailer( pdf), PDF_NAME('Root'))
if root.m_internal:
mupdf.pdf_dict_del( root, PDF_NAME('Metadata'))
def delete_page(self, pno: int =-1):
""" Delete one page from a PDF.
"""
if not self.is_pdf:
raise ValueError("is no PDF")
if self.is_closed:
raise ValueError("document closed")
page_count = self.page_count
while pno < 0:
pno += page_count
if pno >= page_count:
raise ValueError("bad page number(s)")
# remove TOC bookmarks pointing to deleted page
toc = self.get_toc()
ol_xrefs = self.get_outline_xrefs()
for i, item in enumerate(toc):
if item[2] == pno + 1:
self._remove_toc_item(ol_xrefs[i])
self._remove_links_to(frozenset((pno,)))
self._delete_page(pno)
self._reset_page_refs()
def delete_pages(self, *args, **kw):
"""Delete pages from a PDF.
Args:
Either keywords 'from_page'/'to_page', or two integers to
specify the first/last page to delete.
Or a list/tuple/range object, which can contain arbitrary
page numbers.
"""
if not self.is_pdf:
raise ValueError("is no PDF")
if self.is_closed:
raise ValueError("document closed")
page_count = self.page_count # page count of document
f = t = -1
if kw: # check if keywords were used
if args: # then no positional args are allowed
raise ValueError("cannot mix keyword and positional argument")
f = kw.get("from_page", -1) # first page to delete
t = kw.get("to_page", -1) # last page to delete
while f < 0:
f += page_count
while t < 0:
t += page_count
if not f <= t < page_count:
raise ValueError("bad page number(s)")
numbers = tuple(range(f, t + 1))
else:
if len(args) > 2 or args == []:
raise ValueError("need 1 or 2 positional arguments")
if len(args) == 2:
f, t = args
if not (type(f) is int and type(t) is int):
raise ValueError("both arguments must be int")
if f > t:
f, t = t, f
if not f <= t < page_count:
raise ValueError("bad page number(s)")
numbers = tuple(range(f, t + 1))
else:
r = args[0]
if type(r) not in (int, range, list, tuple):
raise ValueError("need int or sequence if one argument")
numbers = tuple(r)
numbers = list(map(int, set(numbers))) # ensure unique integers
if numbers == []:
message("nothing to delete")
return
numbers.sort()
if numbers[0] < 0 or numbers[-1] >= page_count:
raise ValueError("bad page number(s)")
frozen_numbers = frozenset(numbers)
toc = self.get_toc()
for i, xref in enumerate(self.get_outline_xrefs()):
if toc[i][2] - 1 in frozen_numbers:
self._remove_toc_item(xref) # remove target in PDF object
self._remove_links_to(frozen_numbers)
for i in reversed(numbers): # delete pages, last to first
self._delete_page(i)
self._reset_page_refs()
def embfile_add(self,
name: str,
buffer_: typing.ByteString,
filename: OptStr =None,
ufilename: OptStr =None,
desc: OptStr =None,
) -> None:
"""Add an item to the EmbeddedFiles array.
Args:
name: name of the new item, must not already exist.
buffer_: (binary data) the file content.
filename: (str) the file name, default: the name
ufilename: (unicode) the file name, default: filename
desc: (str) the description.
"""
filenames = self.embfile_names()
msg = "Name '%s' already exists." % str(name)
if name in filenames:
raise ValueError(msg)
if filename is None:
filename = name
if ufilename is None:
ufilename = filename
if desc is None:
desc = name
xref = self._embfile_add(
name,
buffer_=buffer_,
filename=filename,
ufilename=ufilename,
desc=desc,
)
date = get_pdf_now()
self.xref_set_key(xref, "Type", "/EmbeddedFile")
self.xref_set_key(xref, "Params/CreationDate", get_pdf_str(date))
self.xref_set_key(xref, "Params/ModDate", get_pdf_str(date))
return xref
def embfile_count(self) -> int:
"""Get number of EmbeddedFiles."""
return len(self.embfile_names())
def embfile_del(self, item: typing.Union[int, str]):
"""Delete an entry from EmbeddedFiles.
Notes:
The argument must be name or index of an EmbeddedFiles item.
Physical deletion of data will happen on save to a new
file with appropriate garbage option.
Args:
item: name or number of item.
Returns:
None
"""
idx = self._embeddedFileIndex(item)
return self._embfile_del(idx)
def embfile_get(self, item: typing.Union[int, str]) -> bytes:
"""Get the content of an item in the EmbeddedFiles array.
Args:
item: number or name of item.
Returns:
(bytes) The file content.
"""
idx = self._embeddedFileIndex(item)
return self._embeddedFileGet(idx)
def embfile_info(self, item: typing.Union[int, str]) -> dict:
"""Get information of an item in the EmbeddedFiles array.
Args:
item: number or name of item.
Returns:
Information dictionary.
"""
idx = self._embeddedFileIndex(item)
infodict = {"name": self.embfile_names()[idx]}
xref = self._embfile_info(idx, infodict)
t, date = self.xref_get_key(xref, "Params/CreationDate")
if t != "null":
infodict["creationDate"] = date
t, date = self.xref_get_key(xref, "Params/ModDate")
if t != "null":
infodict["modDate"] = date
t, md5 = self.xref_get_key(xref, "Params/CheckSum")
if t != "null":
infodict["checksum"] = binascii.hexlify(md5.encode()).decode()
return infodict
def embfile_names(self) -> list:
"""Get list of names of EmbeddedFiles."""
filenames = []
self._embfile_names(filenames)
return filenames
def embfile_upd(self,
item: typing.Union[int, str],
buffer_: OptBytes =None,
filename: OptStr =None,
ufilename: OptStr =None,
desc: OptStr =None,
) -> None:
"""Change an item of the EmbeddedFiles array.
Notes:
Only provided parameters are changed. If all are omitted,
the method is a no-op.
Args:
item: number or name of item.
buffer_: (binary data) the new file content.
filename: (str) the new file name.
ufilename: (unicode) the new filen ame.
desc: (str) the new description.
"""
idx = self._embeddedFileIndex(item)
xref = self._embfile_upd(
idx,
buffer_=buffer_,
filename=filename,
ufilename=ufilename,
desc=desc,
)
date = get_pdf_now()
self.xref_set_key(xref, "Params/ModDate", get_pdf_str(date))
return xref
def extract_font(self, xref=0, info_only=0, named=None):
'''
Get a font by xref. Returns a tuple or dictionary.
'''
#log( '{=xref info_only}')
pdf = _as_pdf_document(self)
obj = mupdf.pdf_load_object(pdf, xref)
type_ = mupdf.pdf_dict_get(obj, PDF_NAME('Type'))
subtype = mupdf.pdf_dict_get(obj, PDF_NAME('Subtype'))
if (mupdf.pdf_name_eq(type_, PDF_NAME('Font'))
and not mupdf.pdf_to_name( subtype).startswith('CIDFontType')
):
basefont = mupdf.pdf_dict_get(obj, PDF_NAME('BaseFont'))
if not basefont.m_internal or mupdf.pdf_is_null(basefont):
bname = mupdf.pdf_dict_get(obj, PDF_NAME('Name'))
else:
bname = basefont
ext = JM_get_fontextension(pdf, xref)
if ext != 'n/a' and not info_only:
buffer_ = JM_get_fontbuffer(pdf, xref)
bytes_ = JM_BinFromBuffer(buffer_)
else:
bytes_ = b''
if not named:
rc = (
JM_EscapeStrFromStr(mupdf.pdf_to_name(bname)),
JM_UnicodeFromStr(ext),
JM_UnicodeFromStr(mupdf.pdf_to_name(subtype)),
bytes_,
)
else:
rc = {
dictkey_name: JM_EscapeStrFromStr(mupdf.pdf_to_name(bname)),
dictkey_ext: JM_UnicodeFromStr(ext),
dictkey_type: JM_UnicodeFromStr(mupdf.pdf_to_name(subtype)),
dictkey_content: bytes_,
}
else:
if not named:
rc = '', '', '', b''
else:
rc = {
dictkey_name: '',
dictkey_ext: '',
dictkey_type: '',
dictkey_content: b'',
}
return rc
def extract_image(self, xref):
"""Get image by xref. Returns a dictionary."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
img_type = 0
smask = 0
if not _INRANGE(xref, 1, mupdf.pdf_xref_len(pdf)-1):
raise ValueError( MSG_BAD_XREF)
obj = mupdf.pdf_new_indirect(pdf, xref, 0)
subtype = mupdf.pdf_dict_get(obj, PDF_NAME('Subtype'))
if not mupdf.pdf_name_eq(subtype, PDF_NAME('Image')):
raise ValueError( "not an image")
o = mupdf.pdf_dict_geta(obj, PDF_NAME('SMask'), PDF_NAME('Mask'))
if o.m_internal:
smask = mupdf.pdf_to_num(o)
if mupdf.pdf_is_jpx_image(obj):
img_type = mupdf.FZ_IMAGE_JPX
res = mupdf.pdf_load_stream(obj)
ext = "jpx"
if JM_is_jbig2_image(obj):
img_type = mupdf.FZ_IMAGE_JBIG2
res = mupdf.pdf_load_stream(obj)
ext = "jb2"
res = mupdf.pdf_load_raw_stream(obj)
if img_type == mupdf.FZ_IMAGE_UNKNOWN:
res = mupdf.pdf_load_raw_stream(obj)
_, c = mupdf.fz_buffer_storage(res)
#log( '{=_ c}')
img_type = mupdf.fz_recognize_image_format(c)
ext = JM_image_extension(img_type)
if img_type == mupdf.FZ_IMAGE_UNKNOWN:
res = None
img = mupdf.pdf_load_image(pdf, obj)
ll_cbuf = mupdf.ll_fz_compressed_image_buffer(img.m_internal)
if (ll_cbuf
and ll_cbuf.params.type not in (
mupdf.FZ_IMAGE_RAW,
mupdf.FZ_IMAGE_FAX,
mupdf.FZ_IMAGE_FLATE,
mupdf.FZ_IMAGE_LZW,
mupdf.FZ_IMAGE_RLD,
)
):
img_type = ll_cbuf.params.type
ext = JM_image_extension(img_type)
res = mupdf.FzBuffer(mupdf.ll_fz_keep_buffer(ll_cbuf.buffer))
else:
res = mupdf.fz_new_buffer_from_image_as_png(
img,
mupdf.FzColorParams(mupdf.fz_default_color_params),
)
ext = "png"
else:
img = mupdf.fz_new_image_from_buffer(res)
xres, yres = mupdf.fz_image_resolution(img)
width = img.w()
height = img.h()
colorspace = img.n()
bpc = img.bpc()
cs_name = mupdf.fz_colorspace_name(img.colorspace())
rc = dict()
rc[ dictkey_ext] = ext
rc[ dictkey_smask] = smask
rc[ dictkey_width] = width
rc[ dictkey_height] = height
rc[ dictkey_colorspace] = colorspace
rc[ dictkey_bpc] = bpc
rc[ dictkey_xres] = xres
rc[ dictkey_yres] = yres
rc[ dictkey_cs_name] = cs_name
rc[ dictkey_image] = JM_BinFromBuffer(res)
return rc
def ez_save(
self,
filename,
garbage=3,
clean=False,
deflate=True,
deflate_images=True,
deflate_fonts=True,
incremental=False,
ascii=False,
expand=False,
linear=False,
pretty=False,
encryption=1,
permissions=4095,
owner_pw=None,
user_pw=None,
no_new_id=True,
preserve_metadata=1,
use_objstms=1,
compression_effort=0,
):
'''
Save PDF using some different defaults
'''
return self.save(
filename,
garbage=garbage,
clean=clean,
deflate=deflate,
deflate_images=deflate_images,
deflate_fonts=deflate_fonts,
incremental=incremental,
ascii=ascii,
expand=expand,
linear=linear,
pretty=pretty,
encryption=encryption,
permissions=permissions,
owner_pw=owner_pw,
user_pw=user_pw,
no_new_id=no_new_id,
preserve_metadata=preserve_metadata,
use_objstms=use_objstms,
compression_effort=compression_effort,
)
def find_bookmark(self, bm):
"""Find new location after layouting a document."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
location = mupdf.fz_lookup_bookmark2( self.this, bm)
return location.chapter, location.page
def fullcopy_page(self, pno, to=-1):
"""Make a full page duplicate."""
pdf = _as_pdf_document(self)
page_count = mupdf.pdf_count_pages( pdf)
try:
if (not _INRANGE(pno, 0, page_count - 1)
or not _INRANGE(to, -1, page_count - 1)
):
raise ValueError( MSG_BAD_PAGENO)
page1 = mupdf.pdf_resolve_indirect( mupdf.pdf_lookup_page_obj( pdf, pno))
page2 = mupdf.pdf_deep_copy_obj( page1)
old_annots = mupdf.pdf_dict_get( page2, PDF_NAME('Annots'))
# copy annotations, but remove Popup and IRT types
if old_annots.m_internal:
n = mupdf.pdf_array_len( old_annots)
new_annots = mupdf.pdf_new_array( pdf, n)
for i in range(n):
o = mupdf.pdf_array_get( old_annots, i)
subtype = mupdf.pdf_dict_get( o, PDF_NAME('Subtype'))
if mupdf.pdf_name_eq( subtype, PDF_NAME('Popup')):
continue
if mupdf.pdf_dict_gets( o, "IRT").m_internal:
continue
copy_o = mupdf.pdf_deep_copy_obj( mupdf.pdf_resolve_indirect( o))
xref = mupdf.pdf_create_object( pdf)
mupdf.pdf_update_object( pdf, xref, copy_o)
copy_o = mupdf.pdf_new_indirect( pdf, xref, 0)
mupdf.pdf_dict_del( copy_o, PDF_NAME('Popup'))
mupdf.pdf_dict_del( copy_o, PDF_NAME('P'))
mupdf.pdf_array_push( new_annots, copy_o)
mupdf.pdf_dict_put( page2, PDF_NAME('Annots'), new_annots)
# copy the old contents stream(s)
res = JM_read_contents( page1)
# create new /Contents object for page2
if res.m_internal:
#contents = mupdf.pdf_add_stream( pdf, mupdf.fz_new_buffer_from_copied_data( b" ", 1), NULL, 0)
contents = mupdf.pdf_add_stream( pdf, mupdf.fz_new_buffer_from_copied_data( b" "), mupdf.PdfObj(), 0)
JM_update_stream( pdf, contents, res, 1)
mupdf.pdf_dict_put( page2, PDF_NAME('Contents'), contents)
# now insert target page, making sure it is an indirect object
xref = mupdf.pdf_create_object( pdf) # get new xref
mupdf.pdf_update_object( pdf, xref, page2) # store new page
page2 = mupdf.pdf_new_indirect( pdf, xref, 0) # reread object
mupdf.pdf_insert_page( pdf, to, page2) # and store the page
finally:
mupdf.ll_pdf_drop_page_tree( pdf.m_internal)
self._reset_page_refs()
def get_layer(self, config=-1):
"""Content of ON, OFF, RBGroups of an OC layer."""
pdf = _as_pdf_document(self)
ocp = mupdf.pdf_dict_getl(
mupdf.pdf_trailer( pdf),
PDF_NAME('Root'),
PDF_NAME('OCProperties'),
)
if not ocp.m_internal:
return
if config == -1:
obj = mupdf.pdf_dict_get( ocp, PDF_NAME('D'))
else:
obj = mupdf.pdf_array_get(
mupdf.pdf_dict_get( ocp, PDF_NAME('Configs')),
config,
)
if not obj.m_internal:
raise ValueError( MSG_BAD_OC_CONFIG)
rc = JM_get_ocg_arrays( obj)
return rc
def get_layers(self):
"""Show optional OC layers."""
pdf = _as_pdf_document(self)
n = mupdf.pdf_count_layer_configs( pdf)
if n == 1:
obj = mupdf.pdf_dict_getl(
mupdf.pdf_trailer( pdf),
PDF_NAME('Root'),
PDF_NAME('OCProperties'),
PDF_NAME('Configs'),
)
if not mupdf.pdf_is_array( obj):
n = 0
rc = []
info = mupdf.PdfLayerConfig()
for i in range(n):
mupdf.pdf_layer_config_info( pdf, i, info)
item = {
"number": i,
"name": info.name,
"creator": info.creator,
}
rc.append( item)
return rc
def get_new_xref(self):
"""Make new xref."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
xref = 0
ENSURE_OPERATION(pdf)
xref = mupdf.pdf_create_object(pdf)
return xref
def get_ocgs(self):
"""Show existing optional content groups."""
ci = mupdf.pdf_new_name( "CreatorInfo")
pdf = _as_pdf_document(self)
ocgs = mupdf.pdf_dict_getl(
mupdf.pdf_dict_get( mupdf.pdf_trailer( pdf), PDF_NAME('Root')),
PDF_NAME('OCProperties'),
PDF_NAME('OCGs'),
)
rc = dict()
if not mupdf.pdf_is_array( ocgs):
return rc
n = mupdf.pdf_array_len( ocgs)
for i in range(n):
ocg = mupdf.pdf_array_get( ocgs, i)
xref = mupdf.pdf_to_num( ocg)
name = mupdf.pdf_to_text_string( mupdf.pdf_dict_get( ocg, PDF_NAME('Name')))
obj = mupdf.pdf_dict_getl( ocg, PDF_NAME('Usage'), ci, PDF_NAME('Subtype'))
usage = None
if obj.m_internal:
usage = mupdf.pdf_to_name( obj)
intents = list()
intent = mupdf.pdf_dict_get( ocg, PDF_NAME('Intent'))
if intent.m_internal:
if mupdf.pdf_is_name( intent):
intents.append( mupdf.pdf_to_name( intent))
elif mupdf.pdf_is_array( intent):
m = mupdf.pdf_array_len( intent)
for j in range(m):
o = mupdf.pdf_array_get( intent, j)
if mupdf.pdf_is_name( o):
intents.append( mupdf.pdf_to_name( o))
hidden = mupdf.pdf_is_ocg_hidden( pdf, mupdf.PdfObj(), usage, ocg)
item = {
"name": name,
"intent": intents,
"on": not hidden,
"usage": usage,
}
temp = xref
rc[ temp] = item
return rc
def get_outline_xrefs(self):
"""Get list of outline xref numbers."""
xrefs = []
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return xrefs
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
if not root.m_internal:
return xrefs
olroot = mupdf.pdf_dict_get(root, PDF_NAME('Outlines'))
if not olroot.m_internal:
return xrefs
first = mupdf.pdf_dict_get(olroot, PDF_NAME('First'))
if not first.m_internal:
return xrefs
xrefs = JM_outline_xrefs(first, xrefs)
return xrefs
def get_page_fonts(self, pno: int, full: bool =False) -> list:
"""Retrieve a list of fonts used on a page.
"""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if not self.is_pdf:
return ()
if type(pno) is not int:
try:
pno = pno.number
except Exception:
exception_info()
raise ValueError("need a Page or page number")
val = self._getPageInfo(pno, 1)
if full is False:
return [v[:-1] for v in val]
return val
def get_page_images(self, pno: int, full: bool =False) -> list:
"""Retrieve a list of images used on a page.
"""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if not self.is_pdf:
return ()
val = self._getPageInfo(pno, 2)
if full is False:
return [v[:-1] for v in val]
return val
def get_page_xobjects(self, pno: int) -> list:
"""Retrieve a list of XObjects used on a page.
"""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if not self.is_pdf:
return ()
val = self._getPageInfo(pno, 3)
return val
def get_sigflags(self):
"""Get the /SigFlags value."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return -1 # not a PDF
sigflags = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('AcroForm'),
PDF_NAME('SigFlags'),
)
sigflag = -1
if sigflags.m_internal:
sigflag = mupdf.pdf_to_int(sigflags)
return sigflag
def get_xml_metadata(self):
"""Get document XML metadata."""
xml = None
pdf = _as_pdf_document(self, required=0)
if pdf.m_internal:
xml = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('Metadata'),
)
if xml is not None and xml.m_internal:
buff = mupdf.pdf_load_stream(xml)
rc = JM_UnicodeFromBuffer(buff)
else:
rc = ''
return rc
def init_doc(self):
if self.is_encrypted:
raise ValueError("cannot initialize - document still encrypted")
self._outline = self._loadOutline()
self.metadata = dict(
[
(k,self._getMetadata(v)) for k,v in {
'format':'format',
'title':'info:Title',
'author':'info:Author',
'subject':'info:Subject',
'keywords':'info:Keywords',
'creator':'info:Creator',
'producer':'info:Producer',
'creationDate':'info:CreationDate',
'modDate':'info:ModDate',
'trapped':'info:Trapped'
}.items()
]
)
self.metadata['encryption'] = None if self._getMetadata('encryption')=='None' else self._getMetadata('encryption')
def insert_file(self,
infile,
from_page=-1,
to_page=-1,
start_at=-1,
rotate=-1,
links=True,
annots=True,
show_progress=0,
final=1,
):
'''
Insert an arbitrary supported document to an existing PDF.
The infile may be given as a filename, a Document or a Pixmap. Other
parameters - where applicable - equal those of insert_pdf().
'''
src = None
if isinstance(infile, Pixmap):
if infile.colorspace.n > 3:
infile = Pixmap(csRGB, infile)
src = Document("png", infile.tobytes())
elif isinstance(infile, Document):
src = infile
else:
src = Document(infile)
if not src:
raise ValueError("bad infile parameter")
if not src.is_pdf:
pdfbytes = src.convert_to_pdf()
src = Document("pdf", pdfbytes)
return self.insert_pdf(
src,
from_page=from_page,
to_page=to_page,
start_at=start_at,
rotate=rotate,
links=links,
annots=annots,
show_progress=show_progress,
final=final,
)
def insert_pdf(
self,
docsrc,
from_page=-1,
to_page=-1,
start_at=-1,
rotate=-1,
links=1,
annots=1,
show_progress=0,
final=1,
_gmap=None,
):
"""Insert a page range from another PDF.
Args:
docsrc: PDF to copy from. Must be different object, but may be same file.
from_page: (int) first source page to copy, 0-based, default 0.
to_page: (int) last source page to copy, 0-based, default last page.
start_at: (int) from_page will become this page number in target.
rotate: (int) rotate copied pages, default -1 is no change.
links: (int/bool) whether to also copy links.
annots: (int/bool) whether to also copy annotations.
show_progress: (int) progress message interval, 0 is no messages.
final: (bool) indicates last insertion from this source PDF.
_gmap: internal use only
Copy sequence reversed if from_page > to_page."""
# Insert pages from a source PDF into this PDF.
# For reconstructing the links (_do_links method), we must save the
# insertion point (start_at) if it was specified as -1.
#log( 'insert_pdf(): start')
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if self._graft_id == docsrc._graft_id:
raise ValueError("source and target cannot be same object")
sa = start_at
if sa < 0:
sa = self.page_count
if len(docsrc) > show_progress > 0:
inname = os.path.basename(docsrc.name)
if not inname:
inname = "memory PDF"
outname = os.path.basename(self.name)
if not outname:
outname = "memory PDF"
message("Inserting '%s' at '%s'" % (inname, outname))
# retrieve / make a Graftmap to avoid duplicate objects
#log( 'insert_pdf(): Graftmaps')
isrt = docsrc._graft_id
_gmap = self.Graftmaps.get(isrt, None)
if _gmap is None:
#log( 'insert_pdf(): Graftmaps2')
_gmap = Graftmap(self)
self.Graftmaps[isrt] = _gmap
if g_use_extra:
#log( 'insert_pdf(): calling extra_FzDocument_insert_pdf()')
extra_FzDocument_insert_pdf(
self.this,
docsrc.this,
from_page,
to_page,
start_at,
rotate,
links,
annots,
show_progress,
final,
_gmap,
)
#log( 'insert_pdf(): extra_FzDocument_insert_pdf() returned.')
else:
pdfout = _as_pdf_document(self)
pdfsrc = _as_pdf_document(docsrc)
outCount = mupdf.fz_count_pages(self)
srcCount = mupdf.fz_count_pages(docsrc.this)
# local copies of page numbers
fp = from_page
tp = to_page
sa = start_at
# normalize page numbers
fp = max(fp, 0) # -1 = first page
fp = min(fp, srcCount - 1) # but do not exceed last page
if tp < 0:
tp = srcCount - 1 # -1 = last page
tp = min(tp, srcCount - 1) # but do not exceed last page
if sa < 0:
sa = outCount # -1 = behind last page
sa = min(sa, outCount) # but that is also the limit
if not pdfout.m_internal or not pdfsrc.m_internal:
raise TypeError( "source or target not a PDF")
ENSURE_OPERATION(pdfout)
JM_merge_range(pdfout, pdfsrc, fp, tp, sa, rotate, links, annots, show_progress, _gmap)
#log( 'insert_pdf(): calling self._reset_page_refs()')
self._reset_page_refs()
if links:
#log( 'insert_pdf(): calling self._do_links()')
self._do_links(docsrc, from_page = from_page, to_page = to_page, start_at = sa)
if final == 1:
self.Graftmaps[isrt] = None
#log( 'insert_pdf(): returning')
@property
def is_dirty(self):
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return False
r = mupdf.pdf_has_unsaved_changes(pdf)
return True if r else False
@property
def is_fast_webaccess(self):
'''
Check whether we have a linearized PDF.
'''
pdf = _as_pdf_document(self, required=0)
if pdf.m_internal:
return mupdf.pdf_doc_was_linearized(pdf)
return False # gracefully handle non-PDF
@property
def is_form_pdf(self):
"""Either False or PDF field count."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return False
count = -1
try:
fields = mupdf.pdf_dict_getl(
mupdf.pdf_trailer(pdf),
mupdf.PDF_ENUM_NAME_Root,
mupdf.PDF_ENUM_NAME_AcroForm,
mupdf.PDF_ENUM_NAME_Fields,
)
if mupdf.pdf_is_array(fields):
count = mupdf.pdf_array_len(fields)
except Exception:
if g_exceptions_verbose: exception_info()
return False
if count >= 0:
return count
return False
@property
def is_pdf(self):
"""Check for PDF."""
if isinstance(self.this, mupdf.PdfDocument):
return True
# Avoid calling smupdf.pdf_specifics because it will end up creating
# a new PdfDocument which will call pdf_create_document(), which is ok
# but a little unnecessary.
#
if mupdf.ll_pdf_specifics(self.this.m_internal):
ret = True
else:
ret = False
return ret
@property
def is_reflowable(self):
"""Check if document is layoutable."""
if self.is_closed:
raise ValueError("document closed")
return bool(mupdf.fz_is_document_reflowable(self))
@property
def is_repaired(self):
"""Check whether PDF was repaired."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return False
r = mupdf.pdf_was_repaired(pdf)
if r:
return True
return False
def journal_can_do(self):
"""Show if undo and / or redo are possible."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
undo=0
redo=0
pdf = _as_pdf_document(self)
undo = mupdf.pdf_can_undo(pdf)
redo = mupdf.pdf_can_redo(pdf)
return {'undo': bool(undo), 'redo': bool(redo)}
def journal_enable(self):
"""Activate document journalling."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
mupdf.pdf_enable_journal(pdf)
def journal_is_enabled(self):
"""Check if journalling is enabled."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
enabled = pdf.m_internal and pdf.m_internal.journal
return enabled
def journal_load(self, filename):
"""Load a journal from a file."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
if isinstance(filename, str):
mupdf.pdf_load_journal(pdf, filename)
else:
res = JM_BufferFromBytes(filename)
stm = mupdf.fz_open_buffer(res)
mupdf.pdf_deserialise_journal(pdf, stm)
if not pdf.m_internal.journal:
RAISEPY( "Journal and document do not match", JM_Exc_FileDataError)
def journal_op_name(self, step):
"""Show operation name for given step."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
name = mupdf.pdf_undoredo_step(pdf, step)
return name
def journal_position(self):
"""Show journalling state."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
steps=0
pdf = _as_pdf_document(self)
rc, steps = mupdf.pdf_undoredo_state(pdf)
return rc, steps
def journal_redo(self):
"""Move forward in the journal."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
mupdf.pdf_redo(pdf)
return True
def journal_save(self, filename):
"""Save journal to a file."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
if isinstance(filename, str):
mupdf.pdf_save_journal(pdf, filename)
else:
out = JM_new_output_fileptr(filename)
mupdf.pdf_write_journal(pdf, out)
out.fz_close_output()
def journal_start_op(self, name=None):
"""Begin a journalling operation."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
if not pdf.m_internal.journal:
raise RuntimeError( "Journalling not enabled")
if name:
mupdf.pdf_begin_operation(pdf, name)
else:
mupdf.pdf_begin_implicit_operation(pdf)
def journal_stop_op(self):
"""End a journalling operation."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
mupdf.pdf_end_operation(pdf)
def journal_undo(self):
"""Move backwards in the journal."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
mupdf.pdf_undo(pdf)
return True
@property
def language(self):
"""Document language."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return
lang = mupdf.pdf_document_language(pdf)
if lang == mupdf.FZ_LANG_UNSET:
return
if mupdf_version_tuple < (1, 23, 7):
assert 0, 'not implemented yet'
return mupdf.fz_string_from_text_language2(lang)
@property
def last_location(self):
"""Id (chapter, page) of last page."""
if self.is_closed:
raise ValueError("document closed")
last_loc = mupdf.fz_last_page(self.this)
return last_loc.chapter, last_loc.page
def layer_ui_configs(self):
"""Show OC visibility status modifiable by user."""
pdf = _as_pdf_document(self)
info = mupdf.PdfLayerConfigUi()
n = mupdf.pdf_count_layer_config_ui( pdf)
rc = []
for i in range(n):
mupdf.pdf_layer_config_ui_info( pdf, i, info)
if info.type == 1:
type_ = "checkbox"
elif info.type == 2:
type_ = "radiobox"
else:
type_ = "label"
item = {
"number": i,
"text": info.text,
"depth": info.depth,
"type": type_,
"on": info.selected,
"locked": info.locked,
}
rc.append(item)
return rc
def layout(self, rect=None, width=0, height=0, fontsize=11):
"""Re-layout a reflowable document."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
doc = self.this
if not mupdf.fz_is_document_reflowable( doc):
return
w = width
h = height
r = JM_rect_from_py(rect)
if not mupdf.fz_is_infinite_rect(r):
w = r.x1 - r.x0
h = r.y1 - r.y0
if w <= 0.0 or h <= 0.0:
raise ValueError( "bad page size")
mupdf.fz_layout_document( doc, w, h, fontsize)
self._reset_page_refs()
self.init_doc()
def load_page(self, page_id):
"""Load a page.
'page_id' is either a 0-based page number or a tuple (chapter, pno),
with chapter number and page number within that chapter.
"""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if page_id is None:
page_id = 0
if page_id not in self:
raise ValueError("page not in document")
if type(page_id) is int and page_id < 0:
np = self.page_count
while page_id < 0:
page_id += np
if isinstance(page_id, int):
page = mupdf.fz_load_page(self.this, page_id)
else:
chapter, pagenum = page_id
page = mupdf.fz_load_chapter_page(self.this, chapter, pagenum)
val = Page(page, self)
val.thisown = True
val.parent = self
self._page_refs[id(val)] = val
val._annot_refs = weakref.WeakValueDictionary()
val.number = page_id
return val
def location_from_page_number(self, pno):
"""Convert pno to (chapter, page)."""
if self.is_closed:
raise ValueError("document closed")
this_doc = self.this
loc = mupdf.fz_make_location(-1, -1)
page_count = mupdf.fz_count_pages(this_doc)
while pno < 0:
pno += page_count
if pno >= page_count:
raise ValueError( MSG_BAD_PAGENO)
loc = mupdf.fz_location_from_page_number(this_doc, pno)
return loc.chapter, loc.page
def make_bookmark(self, loc):
"""Make a page pointer before layouting document."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
loc = mupdf.FzLocation(*loc)
mark = mupdf.ll_fz_make_bookmark2( self.this.m_internal, loc.internal())
return mark
@property
def markinfo(self) -> dict:
"""Return the PDF MarkInfo value."""
xref = self.pdf_catalog()
if xref == 0:
return None
rc = self.xref_get_key(xref, "MarkInfo")
if rc[0] == "null":
return {}
if rc[0] == "xref":
xref = int(rc[1].split()[0])
val = self.xref_object(xref, compressed=True)
elif rc[0] == "dict":
val = rc[1]
else:
val = None
if val is None or not (val[:2] == "<<" and val[-2:] == ">>"):
return {}
valid = {"Marked": False, "UserProperties": False, "Suspects": False}
val = val[2:-2].split("/")
for v in val[1:]:
try:
key, value = v.split()
except Exception:
if g_exceptions_verbose > 1: exception_info()
return valid
if value == "true":
valid[key] = True
return valid
def move_page(self, pno: int, to: int =-1):
"""Move a page within a PDF document.
Args:
pno: source page number.
to: put before this page, '-1' means after last page.
"""
if self.is_closed:
raise ValueError("document closed")
page_count = len(self)
if (pno not in range(page_count) or to not in range(-1, page_count)):
raise ValueError("bad page number(s)")
before = 1
copy = 0
if to == -1:
to = page_count - 1
before = 0
return self._move_copy_page(pno, to, before, copy)
@property
def name(self):
return self._name
def need_appearances(self, value=None):
"""Get/set the NeedAppearances value."""
if not self.is_form_pdf:
return None
pdf = _as_pdf_document(self)
oldval = -1
appkey = "NeedAppearances"
form = mupdf.pdf_dict_getp(
mupdf.pdf_trailer(pdf),
"Root/AcroForm",
)
app = mupdf.pdf_dict_gets(form, appkey)
if mupdf.pdf_is_bool(app):
oldval = mupdf.pdf_to_bool(app)
if value:
mupdf.pdf_dict_puts(form, appkey, mupdf.PDF_TRUE)
else:
mupdf.pdf_dict_puts(form, appkey, mupdf.PDF_FALSE)
if value is None:
return oldval >= 0
return value
@property
def needs_pass(self):
"""Indicate password required."""
if self.is_closed:
raise ValueError("document closed")
document = self.this if isinstance(self.this, mupdf.FzDocument) else self.this.super()
ret = mupdf.fz_needs_password( document)
return ret
def next_location(self, page_id):
"""Get (chapter, page) of next page."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if type(page_id) is int:
page_id = (0, page_id)
if page_id not in self:
raise ValueError("page id not in document")
if tuple(page_id) == self.last_location:
return ()
this_doc = _as_fz_document(self)
val = page_id[ 0]
if not isinstance(val, int):
RAISEPY(MSG_BAD_PAGEID, PyExc_ValueError)
chapter = val
val = page_id[ 1]
pno = val
loc = mupdf.fz_make_location(chapter, pno)
next_loc = mupdf.fz_next_page( this_doc, loc)
return next_loc.chapter, next_loc.page
def page_annot_xrefs(self, n):
if g_use_extra:
return extra.page_annot_xrefs( self.this, n)
if isinstance(self.this, mupdf.PdfDocument):
page_count = mupdf.pdf_count_pages(self.this)
pdf_document = self.this
else:
page_count = mupdf.fz_count_pages(self.this)
pdf_document = _as_pdf_document(self)
while n < 0:
n += page_count
if n > page_count:
raise ValueError( MSG_BAD_PAGENO)
page_obj = mupdf.pdf_lookup_page_obj(pdf_document, n)
annots = JM_get_annot_xref_list(page_obj)
return annots
@property
def page_count(self):
"""Number of pages."""
if self.is_closed:
raise ValueError('document closed')
if g_use_extra:
return self.page_count2(self)
if isinstance( self.this, mupdf.FzDocument):
return mupdf.fz_count_pages( self.this)
else:
return mupdf.pdf_count_pages( self.this)
def page_cropbox(self, pno):
"""Get CropBox of page number (without loading page)."""
if self.is_closed:
raise ValueError("document closed")
this_doc = self.this
page_count = mupdf.fz_count_pages( this_doc)
n = pno
while n < 0:
n += page_count
pdf = _as_pdf_document(self)
if n >= page_count:
raise ValueError( MSG_BAD_PAGENO)
pageref = mupdf.pdf_lookup_page_obj( pdf, n)
cropbox = JM_cropbox(pageref)
val = JM_py_from_rect(cropbox)
val = Rect(val)
return val
def page_number_from_location(self, page_id):
"""Convert (chapter, pno) to page number."""
if type(page_id) is int:
np = self.page_count
while page_id < 0:
page_id += np
page_id = (0, page_id)
if page_id not in self:
raise ValueError("page id not in document")
chapter, pno = page_id
loc = mupdf.fz_make_location( chapter, pno)
page_n = mupdf.fz_page_number_from_location( self.this, loc)
return page_n
def page_xref(self, pno):
"""Get xref of page number."""
if g_use_extra:
return extra.page_xref( self.this, pno)
if self.is_closed:
raise ValueError("document closed")
page_count = mupdf.fz_count_pages(self.this)
n = pno
while n < 0:
n += page_count
pdf = _as_pdf_document(self)
xref = 0
if n >= page_count:
raise ValueError( MSG_BAD_PAGENO)
xref = mupdf.pdf_to_num(mupdf.pdf_lookup_page_obj(pdf, n))
return xref
@property
def pagelayout(self) -> str:
"""Return the PDF PageLayout value.
"""
xref = self.pdf_catalog()
if xref == 0:
return None
rc = self.xref_get_key(xref, "PageLayout")
if rc[0] == "null":
return "SinglePage"
if rc[0] == "name":
return rc[1][1:]
return "SinglePage"
@property
def pagemode(self) -> str:
"""Return the PDF PageMode value.
"""
xref = self.pdf_catalog()
if xref == 0:
return None
rc = self.xref_get_key(xref, "PageMode")
if rc[0] == "null":
return "UseNone"
if rc[0] == "name":
return rc[1][1:]
return "UseNone"
if sys.implementation.version < (3, 9):
# Appending `[Page]` causes `TypeError: 'ABCMeta' object is not subscriptable`.
_pages_ret = collections.abc.Iterable
else:
_pages_ret = collections.abc.Iterable[Page]
def pages(self, start: OptInt =None, stop: OptInt =None, step: OptInt =None) -> _pages_ret:
"""Return a generator iterator over a page range.
Arguments have the same meaning as for the range() built-in.
"""
# set the start value
start = start or 0
while start < 0:
start += self.page_count
if start not in range(self.page_count):
raise ValueError("bad start page number")
# set the stop value
stop = stop if stop is not None and stop <= self.page_count else self.page_count
# set the step value
if step == 0:
raise ValueError("arg 3 must not be zero")
if step is None:
if start > stop:
step = -1
else:
step = 1
for pno in range(start, stop, step):
yield (self.load_page(pno))
def pdf_catalog(self):
"""Get xref of PDF catalog."""
pdf = _as_pdf_document(self, required=0)
xref = 0
if not pdf.m_internal:
return xref
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
xref = mupdf.pdf_to_num(root)
return xref
def pdf_trailer(self, compressed=0, ascii=0):
"""Get PDF trailer as a string."""
return self.xref_object(-1, compressed=compressed, ascii=ascii)
@property
def permissions(self):
"""Document permissions."""
if self.is_encrypted:
return 0
doc =self.this
pdf = mupdf.pdf_document_from_fz_document(doc)
# for PDF return result of standard function
if pdf.m_internal:
return mupdf.pdf_document_permissions(pdf)
# otherwise simulate the PDF return value
perm = 0xFFFFFFFC # all permissions granted
# now switch off where needed
if not mupdf.fz_has_permission(doc, mupdf.FZ_PERMISSION_PRINT):
perm = perm ^ mupdf.PDF_PERM_PRINT
if not mupdf.fz_has_permission(doc, mupdf.FZ_PERMISSION_EDIT):
perm = perm ^ mupdf.PDF_PERM_MODIFY
if not mupdf.fz_has_permission(doc, mupdf.FZ_PERMISSION_COPY):
perm = perm ^ mupdf.PDF_PERM_COPY
if not mupdf.fz_has_permission(doc, mupdf.FZ_PERMISSION_ANNOTATE):
perm = perm ^ mupdf.PDF_PERM_ANNOTATE
return perm
def prev_location(self, page_id):
"""Get (chapter, page) of previous page."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if type(page_id) is int:
page_id = (0, page_id)
if page_id not in self:
raise ValueError("page id not in document")
if page_id == (0, 0):
return ()
chapter, pno = page_id
loc = mupdf.fz_make_location(chapter, pno)
prev_loc = mupdf.fz_previous_page(self.this, loc)
return prev_loc.chapter, prev_loc.page
def reload_page(self, page: Page) -> Page:
"""Make a fresh copy of a page."""
old_annots = {} # copy annot references to here
pno = page.number # save the page number
for k, v in page._annot_refs.items(): # save the annot dictionary
old_annots[k] = v
# When we call `self.load_page()` below, it will end up in
# fz_load_chapter_page(), which will return any matching page in the
# document's list of non-ref-counted loaded pages, instead of actually
# reloading the page.
#
# We want to assert that we have actually reloaded the fz_page, and not
# simply returned the same `fz_page*` pointer from the document's list
# of non-ref-counted loaded pages.
#
# So we first remove our reference to the `fz_page*`. This will
# decrement .refs, and if .refs was 1, this is guaranteed to free the
# `fz_page*` and remove it from the document's list if it was there. So
# we are guaranteed that our returned `fz_page*` is from a genuine
# reload, even if it happens to reuse the original block of memory.
#
# However if the original .refs is greater than one, there must be
# other references to the `fz_page` somewhere, and we require that
# these other references are not keeping the page in the document's
# list. We check that we are returning a newly loaded page by
# asserting that our returned `fz_page*` is different from the original
# `fz_page*` - the original was not freed, so a new `fz_page` cannot
# reuse the same block of memory.
#
refs_old = page.this.m_internal.refs
m_internal_old = page.this.m_internal_value()
page.this = None
page._erase() # remove the page
page = None
TOOLS.store_shrink(100)
page = self.load_page(pno) # reload the page
# copy annot refs over to the new dictionary
#page_proxy = weakref.proxy(page)
for k, v in old_annots.items():
annot = old_annots[k]
#annot.parent = page_proxy # refresh parent to new page
page._annot_refs[k] = annot
if refs_old == 1:
# We know that `page.this = None` will have decremented the ref
# count to zero so we are guaranteed that the new `fz_page` is a
# new page even if it happens to have reused the same block of
# memory.
pass
else:
# Check that the new `fz_page*` is different from the original.
m_internal_new = page.this.m_internal_value()
assert m_internal_new != m_internal_old, \
f'{refs_old=} {m_internal_old=:#x} {m_internal_new=:#x}'
return page
def resolve_link(self, uri=None, chapters=0):
"""Calculate internal link destination.
Args:
uri: (str) some Link.uri
chapters: (bool) whether to use (chapter, page) format
Returns:
(page_id, x, y) where x, y are point coordinates on the page.
page_id is either page number (if chapters=0), or (chapter, pno).
"""
if not uri:
if chapters:
return (-1, -1), 0, 0
return -1, 0, 0
try:
loc, xp, yp = mupdf.fz_resolve_link(self.this, uri)
except Exception:
if g_exceptions_verbose: exception_info()
if chapters:
return (-1, -1), 0, 0
return -1, 0, 0
if chapters:
return (loc.chapter, loc.page), xp, yp
pno = mupdf.fz_page_number_from_location(self.this, loc)
return pno, xp, yp
def resolve_names(self):
"""Convert the PDF's destination names into a Python dict.
The only parameter is the pymupdf.Document.
All names found in the catalog under keys "/Dests" and "/Names/Dests" are
being included.
Returns:
A dcitionary with the following layout:
- key: (str) the name
- value: (dict) with the following layout:
* "page": target page number (0-based). If no page number found -1.
* "to": (x, y) target point on page - currently in PDF coordinates,
i.e. point (0,0) is the bottom-left of the page.
* "zoom": (float) the zoom factor
* "dest": (str) only occurs if the target location on the page has
not been provided as "/XYZ" or if no page number was found.
Examples:
{'__bookmark_1': {'page': 0, 'to': (0.0, 541.0), 'zoom': 0.0},
'__bookmark_2': {'page': 0, 'to': (0.0, 481.45), 'zoom': 0.0}}
or
'21154a7c20684ceb91f9c9adc3b677c40': {'page': -1, 'dest': '/XYZ 15.75 1486 0'}, ...
"""
if hasattr(self, "_resolved_names"): # do not execute multiple times!
return self._resolved_names
# this is a backward listing of page xref to page number
page_xrefs = {self.page_xref(i): i for i in range(self.page_count)}
def obj_string(obj):
"""Return string version of a PDF object definition."""
buffer = mupdf.fz_new_buffer(512)
output = mupdf.FzOutput(buffer)
mupdf.pdf_print_obj(output, obj, 1, 0)
output.fz_close_output()
return JM_UnicodeFromBuffer(buffer)
def get_array(val):
"""Generate value of one item of the names dictionary."""
templ_dict = {"page": -1, "dest": ""} # value template
if val.pdf_is_indirect():
val = mupdf.pdf_resolve_indirect(val)
if val.pdf_is_array():
array = obj_string(val)
elif val.pdf_is_dict():
array = obj_string(mupdf.pdf_dict_gets(val, "D"))
else: # if all fails return the empty template
return templ_dict
# replace PDF "null" by zero, omit the square brackets
array = array.replace("null", "0")[1:-1]
# find stuff before first "/"
idx = array.find("/")
if idx < 1: # this has no target page spec
templ_dict["dest"] = array # return the orig. string
return templ_dict
subval = array[:idx] # stuff before "/"
array = array[idx:] # stuff from "/" onwards
templ_dict["dest"] = array
# if we start with /XYZ: extract x, y, zoom
# 1, 2 or 3 of these values may actually be supplied
if array.startswith("/XYZ"):
del templ_dict["dest"] # don't return orig string in this case
t = [0, 0, 0] # the resulting x, y, z values
# need to replace any "null" item by "0", then split at
# white spaces, omitting "/XYZ" from the result
for i, v in enumerate(array.replace("null", "0").split()[1:]):
t[i] = float(v)
templ_dict["to"] = (t[0], t[1])
templ_dict["zoom"] = t[2]
# extract page number
if "0 R" in subval: # page xref given?
templ_dict["page"] = page_xrefs.get(int(subval.split()[0]),-1)
else: # naked page number given
templ_dict["page"] = int(subval)
return templ_dict
def fill_dict(dest_dict, pdf_dict):
"""Generate name resolution items for pdf_dict.
This may be either "/Names/Dests" or just "/Dests"
"""
# length of the PDF dictionary
name_count = mupdf.pdf_dict_len(pdf_dict)
# extract key-val of each dict item
for i in range(name_count):
key = mupdf.pdf_dict_get_key(pdf_dict, i)
val = mupdf.pdf_dict_get_val(pdf_dict, i)
if key.pdf_is_name(): # this should always be true!
dict_key = key.pdf_to_name()
else:
message(f"key {i} is no /Name")
dict_key = None
if dict_key:
dest_dict[dict_key] = get_array(val) # store key/value in dict
# access underlying PDF document of fz Document
pdf = mupdf.pdf_document_from_fz_document(self)
# access PDF catalog
catalog = mupdf.pdf_dict_gets(mupdf.pdf_trailer(pdf), "Root")
dest_dict = {}
# make PDF_NAME(Dests)
dests = mupdf.pdf_new_name("Dests")
# extract destinations old style (PDF 1.1)
old_dests = mupdf.pdf_dict_get(catalog, dests)
if old_dests.pdf_is_dict():
fill_dict(dest_dict, old_dests)
# extract destinations new style (PDF 1.2+)
tree = mupdf.pdf_load_name_tree(pdf, dests)
if tree.pdf_is_dict():
fill_dict(dest_dict, tree)
self._resolved_names = dest_dict # store result or reuse
return dest_dict
def save(
self,
filename,
garbage=0,
clean=0,
deflate=0,
deflate_images=0,
deflate_fonts=0,
incremental=0,
ascii=0,
expand=0,
linear=0,
no_new_id=0,
appearance=0,
pretty=0,
encryption=1,
permissions=4095,
owner_pw=None,
user_pw=None,
preserve_metadata=1,
use_objstms=0,
compression_effort=0,
):
# From %pythonprepend save
#
"""Save PDF to file, pathlib.Path or file pointer."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if type(filename) is str:
pass
elif hasattr(filename, "open"): # assume: pathlib.Path
filename = str(filename)
elif hasattr(filename, "name"): # assume: file object
filename = filename.name
elif not hasattr(filename, "seek"): # assume file object
raise ValueError("filename must be str, Path or file object")
if filename == self.name and not incremental:
raise ValueError("save to original must be incremental")
if linear and use_objstms:
raise ValueError("'linear' and 'use_objstms' cannot both be requested")
if self.page_count < 1:
raise ValueError("cannot save with zero pages")
if incremental:
if self.name != filename or self.stream:
raise ValueError("incremental needs original file")
if user_pw and len(user_pw) > 40 or owner_pw and len(owner_pw) > 40:
raise ValueError("password length must not exceed 40")
pdf = _as_pdf_document(self)
opts = mupdf.PdfWriteOptions()
opts.do_incremental = incremental
opts.do_ascii = ascii
opts.do_compress = deflate
opts.do_compress_images = deflate_images
opts.do_compress_fonts = deflate_fonts
opts.do_decompress = expand
opts.do_garbage = garbage
opts.do_pretty = pretty
opts.do_linear = linear
opts.do_clean = clean
opts.do_sanitize = clean
opts.dont_regenerate_id = no_new_id
opts.do_appearance = appearance
opts.do_encrypt = encryption
opts.permissions = permissions
if owner_pw is not None:
opts.opwd_utf8_set_value(owner_pw)
elif user_pw is not None:
opts.opwd_utf8_set_value(user_pw)
if user_pw is not None:
opts.upwd_utf8_set_value(user_pw)
opts.do_preserve_metadata = preserve_metadata
opts.do_use_objstms = use_objstms
opts.compression_effort = compression_effort
out = None
pdf.m_internal.resynth_required = 0
JM_embedded_clean(pdf)
if no_new_id == 0:
JM_ensure_identity(pdf)
if isinstance(filename, str):
#log( 'calling mupdf.pdf_save_document()')
mupdf.pdf_save_document(pdf, filename, opts)
else:
out = JM_new_output_fileptr(filename)
#log( f'{type(out)=} {type(out.this)=}')
mupdf.pdf_write_document(pdf, out, opts)
out.fz_close_output()
def save_snapshot(self, filename):
"""Save a file snapshot suitable for journalling."""
if self.is_closed:
raise ValueError("doc is closed")
if type(filename) is str:
pass
elif hasattr(filename, "open"): # assume: pathlib.Path
filename = str(filename)
elif hasattr(filename, "name"): # assume: file object
filename = filename.name
else:
raise ValueError("filename must be str, Path or file object")
if filename == self.name:
raise ValueError("cannot snapshot to original")
pdf = _as_pdf_document(self)
mupdf.pdf_save_snapshot(pdf, filename)
def saveIncr(self):
""" Save PDF incrementally"""
return self.save(self.name, incremental=True, encryption=mupdf.PDF_ENCRYPT_KEEP)
def select(self, pyliste):
"""Build sub-pdf with page numbers in the list."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if not self.is_pdf:
raise ValueError("is no PDF")
if not hasattr(pyliste, "__getitem__"):
raise ValueError("sequence required")
valid_range = range(len(self))
if (len(pyliste) == 0
or min(pyliste) not in valid_range
or max(pyliste) not in valid_range
):
raise ValueError("bad page number(s)")
# get underlying pdf document,
pdf = _as_pdf_document(self)
# create page sub-pdf via pdf_rearrange_pages2().
#
if mupdf_version_tuple >= (1, 24):
mupdf.pdf_rearrange_pages2(pdf, pyliste)
else:
# mupdf.pdf_rearrange_pages2() not available.
extra.rearrange_pages2(pdf, tuple(pyliste))
# remove any existing pages with their kids
self._reset_page_refs()
def set_language(self, language=None):
pdf = _as_pdf_document(self)
if not language:
lang = mupdf.FZ_LANG_UNSET
else:
lang = mupdf.fz_text_language_from_string(language)
mupdf.pdf_set_document_language(pdf, lang)
return True
def set_layer(self, config, basestate=None, on=None, off=None, rbgroups=None, locked=None):
"""Set the PDF keys /ON, /OFF, /RBGroups of an OC layer."""
if self.is_closed:
raise ValueError("document closed")
ocgs = set(self.get_ocgs().keys())
if ocgs == set():
raise ValueError("document has no optional content")
if on:
if type(on) not in (list, tuple):
raise ValueError("bad type: 'on'")
s = set(on).difference(ocgs)
if s != set():
raise ValueError("bad OCGs in 'on': %s" % s)
if off:
if type(off) not in (list, tuple):
raise ValueError("bad type: 'off'")
s = set(off).difference(ocgs)
if s != set():
raise ValueError("bad OCGs in 'off': %s" % s)
if locked:
if type(locked) not in (list, tuple):
raise ValueError("bad type: 'locked'")
s = set(locked).difference(ocgs)
if s != set():
raise ValueError("bad OCGs in 'locked': %s" % s)
if rbgroups:
if type(rbgroups) not in (list, tuple):
raise ValueError("bad type: 'rbgroups'")
for x in rbgroups:
if not type(x) in (list, tuple):
raise ValueError("bad RBGroup '%s'" % x)
s = set(x).difference(ocgs)
if s != set():
raise ValueError("bad OCGs in RBGroup: %s" % s)
if basestate:
basestate = str(basestate).upper()
if basestate == "UNCHANGED":
basestate = "Unchanged"
if basestate not in ("ON", "OFF", "Unchanged"):
raise ValueError("bad 'basestate'")
pdf = _as_pdf_document(self)
ocp = mupdf.pdf_dict_getl(
mupdf.pdf_trailer( pdf),
PDF_NAME('Root'),
PDF_NAME('OCProperties'),
)
if not ocp.m_internal:
return
if config == -1:
obj = mupdf.pdf_dict_get( ocp, PDF_NAME('D'))
else:
obj = mupdf.pdf_array_get(
mupdf.pdf_dict_get( ocp, PDF_NAME('Configs')),
config,
)
if not obj.m_internal:
raise ValueError( MSG_BAD_OC_CONFIG)
JM_set_ocg_arrays( obj, basestate, on, off, rbgroups, locked)
mupdf.ll_pdf_read_ocg( pdf.m_internal)
def set_layer_ui_config(self, number, action=0):
"""Set / unset OC intent configuration."""
# The user might have given the name instead of sequence number,
# so select by that name and continue with corresp. number
if isinstance(number, str):
select = [ui["number"] for ui in self.layer_ui_configs() if ui["text"] == number]
if select == []:
raise ValueError(f"bad OCG '{number}'.")
number = select[0] # this is the number for the name
pdf = _as_pdf_document(self)
if action == 1:
mupdf.pdf_toggle_layer_config_ui(pdf, number)
elif action == 2:
mupdf.pdf_deselect_layer_config_ui(pdf, number)
else:
mupdf.pdf_select_layer_config_ui(pdf, number)
def set_markinfo(self, markinfo: dict) -> bool:
"""Set the PDF MarkInfo values."""
xref = self.pdf_catalog()
if xref == 0:
raise ValueError("not a PDF")
if not markinfo or not isinstance(markinfo, dict):
return False
valid = {"Marked": False, "UserProperties": False, "Suspects": False}
if not set(valid.keys()).issuperset(markinfo.keys()):
badkeys = f"bad MarkInfo key(s): {set(markinfo.keys()).difference(valid.keys())}"
raise ValueError(badkeys)
pdfdict = "<<"
valid.update(markinfo)
for key, value in valid.items():
value=str(value).lower()
if value not in ("true", "false"):
raise ValueError(f"bad key value '{key}': '{value}'")
pdfdict += f"/{key} {value}"
pdfdict += ">>"
self.xref_set_key(xref, "MarkInfo", pdfdict)
return True
def set_pagelayout(self, pagelayout: str):
"""Set the PDF PageLayout value."""
valid = ("SinglePage", "OneColumn", "TwoColumnLeft", "TwoColumnRight", "TwoPageLeft", "TwoPageRight")
xref = self.pdf_catalog()
if xref == 0:
raise ValueError("not a PDF")
if not pagelayout:
raise ValueError("bad PageLayout value")
if pagelayout[0] == "/":
pagelayout = pagelayout[1:]
for v in valid:
if pagelayout.lower() == v.lower():
self.xref_set_key(xref, "PageLayout", f"/{v}")
return True
raise ValueError("bad PageLayout value")
def set_pagemode(self, pagemode: str):
"""Set the PDF PageMode value."""
valid = ("UseNone", "UseOutlines", "UseThumbs", "FullScreen", "UseOC", "UseAttachments")
xref = self.pdf_catalog()
if xref == 0:
raise ValueError("not a PDF")
if not pagemode:
raise ValueError("bad PageMode value")
if pagemode[0] == "/":
pagemode = pagemode[1:]
for v in valid:
if pagemode.lower() == v.lower():
self.xref_set_key(xref, "PageMode", f"/{v}")
return True
raise ValueError("bad PageMode value")
def set_xml_metadata(self, metadata):
"""Store XML document level metadata."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
root = mupdf.pdf_dict_get( mupdf.pdf_trailer( pdf), PDF_NAME('Root'))
if not root.m_internal:
RAISEPY( MSG_BAD_PDFROOT, JM_Exc_FileDataError)
res = mupdf.fz_new_buffer_from_copied_data( metadata.encode('utf-8'))
xml = mupdf.pdf_dict_get( root, PDF_NAME('Metadata'))
if xml.m_internal:
JM_update_stream( pdf, xml, res, 0)
else:
xml = mupdf.pdf_add_stream( pdf, res, mupdf.PdfObj(), 0)
mupdf.pdf_dict_put( xml, PDF_NAME('Type'), PDF_NAME('Metadata'))
mupdf.pdf_dict_put( xml, PDF_NAME('Subtype'), PDF_NAME('XML'))
mupdf.pdf_dict_put( root, PDF_NAME('Metadata'), xml)
def switch_layer(self, config, as_default=0):
"""Activate an OC layer."""
pdf = _as_pdf_document(self)
cfgs = mupdf.pdf_dict_getl(
mupdf.pdf_trailer( pdf),
PDF_NAME('Root'),
PDF_NAME('OCProperties'),
PDF_NAME('Configs')
)
if not mupdf.pdf_is_array( cfgs) or not mupdf.pdf_array_len( cfgs):
if config < 1:
return
raise ValueError( MSG_BAD_OC_LAYER)
if config < 0:
return
mupdf.pdf_select_layer_config( pdf, config)
if as_default:
mupdf.pdf_set_layer_config_as_default( pdf)
mupdf.ll_pdf_read_ocg( pdf.m_internal)
def update_object(self, xref, text, page=None):
"""Replace object definition source."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len(pdf)
if not _INRANGE(xref, 1, xreflen-1):
RAISEPY("bad xref", MSG_BAD_XREF, PyExc_ValueError)
ENSURE_OPERATION(pdf)
# create new object with passed-in string
new_obj = JM_pdf_obj_from_str(pdf, text)
mupdf.pdf_update_object(pdf, xref, new_obj)
if page:
JM_refresh_links( _as_pdf_page(page))
def update_stream(self, xref=0, stream=None, new=1, compress=1):
"""Replace xref stream part."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len(pdf)
if xref < 1 or xref > xreflen:
raise ValueError( MSG_BAD_XREF)
# get the object
obj = mupdf.pdf_new_indirect(pdf, xref, 0)
if not mupdf.pdf_is_dict(obj):
raise ValueError( MSG_IS_NO_DICT)
res = JM_BufferFromBytes(stream)
if not res.m_internal:
raise TypeError( MSG_BAD_BUFFER)
JM_update_stream(pdf, obj, res, compress)
pdf.dirty = 1
@property
def version_count(self):
'''
Count versions of PDF document.
'''
pdf = _as_pdf_document(self, required=0)
if pdf.m_internal:
return mupdf.pdf_count_versions(pdf)
return 0
def write(
self,
garbage=False,
clean=False,
deflate=False,
deflate_images=False,
deflate_fonts=False,
incremental=False,
ascii=False,
expand=False,
linear=False,
no_new_id=False,
appearance=False,
pretty=False,
encryption=1,
permissions=4095,
owner_pw=None,
user_pw=None,
preserve_metadata=1,
use_objstms=0,
compression_effort=0,
):
from io import BytesIO
bio = BytesIO()
self.save(
bio,
garbage=garbage,
clean=clean,
no_new_id=no_new_id,
appearance=appearance,
deflate=deflate,
deflate_images=deflate_images,
deflate_fonts=deflate_fonts,
incremental=incremental,
ascii=ascii,
expand=expand,
linear=linear,
pretty=pretty,
encryption=encryption,
permissions=permissions,
owner_pw=owner_pw,
user_pw=user_pw,
preserve_metadata=preserve_metadata,
use_objstms=use_objstms,
compression_effort=compression_effort,
)
return bio.getvalue()
@property
def xref(self):
"""PDF xref number of page."""
CheckParent(self)
return self.parent.page_xref(self.number)
def xref_get_key(self, xref, key):
"""Get PDF dict key value of object at 'xref'."""
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len(pdf)
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref > 0:
obj = mupdf.pdf_load_object(pdf, xref)
else:
obj = mupdf.pdf_trailer(pdf)
if not obj.m_internal:
return ("null", "null")
subobj = mupdf.pdf_dict_getp(obj, key)
if not subobj.m_internal:
return ("null", "null")
text = None
if mupdf.pdf_is_indirect(subobj):
type = "xref"
text = "%i 0 R" % mupdf.pdf_to_num(subobj)
elif mupdf.pdf_is_array(subobj):
type = "array"
elif mupdf.pdf_is_dict(subobj):
type = "dict"
elif mupdf.pdf_is_int(subobj):
type = "int"
text = "%i" % mupdf.pdf_to_int(subobj)
elif mupdf.pdf_is_real(subobj):
type = "float"
elif mupdf.pdf_is_null(subobj):
type = "null"
text = "null"
elif mupdf.pdf_is_bool(subobj):
type = "bool"
if mupdf.pdf_to_bool(subobj):
text = "true"
else:
text = "false"
elif mupdf.pdf_is_name(subobj):
type = "name"
text = "/%s" % mupdf.pdf_to_name(subobj)
elif mupdf.pdf_is_string(subobj):
type = "string"
text = JM_UnicodeFromStr(mupdf.pdf_to_text_string(subobj))
else:
type = "unknown"
if text is None:
res = JM_object_to_buffer(subobj, 1, 0)
text = JM_UnicodeFromBuffer(res)
return (type, text)
def xref_get_keys(self, xref):
"""Get the keys of PDF dict object at 'xref'. Use -1 for the PDF trailer."""
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len( pdf)
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref > 0:
obj = mupdf.pdf_load_object( pdf, xref)
else:
obj = mupdf.pdf_trailer( pdf)
n = mupdf.pdf_dict_len( obj)
rc = []
if n == 0:
return rc
for i in range(n):
key = mupdf.pdf_to_name( mupdf.pdf_dict_get_key( obj, i))
rc.append(key)
return rc
def xref_is_font(self, xref):
"""Check if xref is a font object."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if self.xref_get_key(xref, "Type")[1] == "/Font":
return True
return False
def xref_is_image(self, xref):
"""Check if xref is an image object."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if self.xref_get_key(xref, "Subtype")[1] == "/Image":
return True
return False
def xref_is_stream(self, xref=0):
"""Check if xref is a stream object."""
pdf = _as_pdf_document(self, required=0)
if not pdf.m_internal:
return False # not a PDF
return bool(mupdf.pdf_obj_num_is_stream(pdf, xref))
def xref_is_xobject(self, xref):
"""Check if xref is a form xobject."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
if self.xref_get_key(xref, "Subtype")[1] == "/Form":
return True
return False
def xref_length(self):
"""Get length of xref table."""
xreflen = 0
pdf = _as_pdf_document(self, required=0)
if pdf.m_internal:
xreflen = mupdf.pdf_xref_len(pdf)
return xreflen
def xref_object(self, xref, compressed=0, ascii=0):
"""Get xref object source as a string."""
if self.is_closed:
raise ValueError("document closed")
if g_use_extra:
ret = extra.xref_object( self.this, xref, compressed, ascii)
return ret
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len(pdf)
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref > 0:
obj = mupdf.pdf_load_object(pdf, xref)
else:
obj = mupdf.pdf_trailer(pdf)
res = JM_object_to_buffer(mupdf.pdf_resolve_indirect(obj), compressed, ascii)
text = JM_EscapeStrFromBuffer(res)
return text
def xref_set_key(self, xref, key, value):
"""Set the value of a PDF dictionary key."""
if self.is_closed:
raise ValueError("document closed")
if not key or not isinstance(key, str) or INVALID_NAME_CHARS.intersection(key) not in (set(), {"/"}):
raise ValueError("bad 'key'")
if not isinstance(value, str) or not value or value[0] == "/" and INVALID_NAME_CHARS.intersection(value[1:]) != set():
raise ValueError("bad 'value'")
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len(pdf)
#if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
# THROWMSG("bad xref")
#if len(value) == 0:
# THROWMSG("bad 'value'")
#if len(key) == 0:
# THROWMSG("bad 'key'")
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref != -1:
obj = mupdf.pdf_load_object(pdf, xref)
else:
obj = mupdf.pdf_trailer(pdf)
new_obj = JM_set_object_value(obj, key, value)
if not new_obj.m_internal:
return # did not work: skip update
if xref != -1:
mupdf.pdf_update_object(pdf, xref, new_obj)
else:
n = mupdf.pdf_dict_len(new_obj)
for i in range(n):
mupdf.pdf_dict_put(
obj,
mupdf.pdf_dict_get_key(new_obj, i),
mupdf.pdf_dict_get_val(new_obj, i),
)
def xref_stream(self, xref):
"""Get decompressed xref stream."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len( pdf)
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref >= 0:
obj = mupdf.pdf_new_indirect( pdf, xref, 0)
else:
obj = mupdf.pdf_trailer( pdf)
r = None
if mupdf.pdf_is_stream( obj):
res = mupdf.pdf_load_stream_number( pdf, xref)
r = JM_BinFromBuffer( res)
return r
def xref_stream_raw(self, xref):
"""Get xref stream without decompression."""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
pdf = _as_pdf_document(self)
xreflen = mupdf.pdf_xref_len( pdf)
if not _INRANGE(xref, 1, xreflen-1) and xref != -1:
raise ValueError( MSG_BAD_XREF)
if xref >= 0:
obj = mupdf.pdf_new_indirect( pdf, xref, 0)
else:
obj = mupdf.pdf_trailer( pdf)
r = None
if mupdf.pdf_is_stream( obj):
res = mupdf.pdf_load_raw_stream_number( pdf, xref)
r = JM_BinFromBuffer( res)
return r
def xref_xml_metadata(self):
"""Get xref of document XML metadata."""
pdf = _as_pdf_document(self)
root = mupdf.pdf_dict_get( mupdf.pdf_trailer( pdf), PDF_NAME('Root'))
if not root.m_internal:
RAISEPY( MSG_BAD_PDFROOT, JM_Exc_FileDataError)
xml = mupdf.pdf_dict_get( root, PDF_NAME('Metadata'))
xref = 0
if xml.m_internal:
xref = mupdf.pdf_to_num( xml)
return xref
__slots__ = ('this', 'page_count2', 'this_is_pdf', '__dict__')
outline = property(lambda self: self._outline)
tobytes = write
is_stream = xref_is_stream
open = Document
class DocumentWriter:
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def __init__(self, path, options=''):
if isinstance( path, str):
pass
elif hasattr( path, 'absolute'):
path = str( path)
elif hasattr( path, 'name'):
path = path.name
if isinstance( path, str):
self.this = mupdf.FzDocumentWriter( path, options, mupdf.FzDocumentWriter.PathType_PDF)
else:
# Need to keep the Python JM_new_output_fileptr_Output instance
# alive for the lifetime of this DocumentWriter, otherwise calls
# to virtual methods implemented in Python fail. So we make it a
# member of this DocumentWriter.
#
# Unrelated to this, mupdf.FzDocumentWriter will set
# self._out.m_internal to null because ownership is passed in.
#
out = JM_new_output_fileptr( path)
self.this = mupdf.FzDocumentWriter( out, options, mupdf.FzDocumentWriter.OutputType_PDF)
assert out.m_internal_value() == 0
assert hasattr( self.this, '_out')
def begin_page( self, mediabox):
mediabox2 = JM_rect_from_py(mediabox)
device = mupdf.fz_begin_page( self.this, mediabox2)
device_wrapper = DeviceWrapper( device)
return device_wrapper
def close( self):
mupdf.fz_close_document_writer( self.this)
def end_page( self):
mupdf.fz_end_page( self.this)
class Font:
def __del__(self):
if type(self) is not Font:
return None
def __init__(
self,
fontname=None,
fontfile=None,
fontbuffer=None,
script=0,
language=None,
ordering=-1,
is_bold=0,
is_italic=0,
is_serif=0,
embed=1,
):
if fontbuffer:
if hasattr(fontbuffer, "getvalue"):
fontbuffer = fontbuffer.getvalue()
elif isinstance(fontbuffer, bytearray):
fontbuffer = bytes(fontbuffer)
if not isinstance(fontbuffer, bytes):
raise ValueError("bad type: 'fontbuffer'")
if isinstance(fontname, str):
fname_lower = fontname.lower()
if "/" in fname_lower or "\\" in fname_lower or "." in fname_lower:
message("Warning: did you mean a fontfile?")
if fname_lower in ("cjk", "china-t", "china-ts"):
ordering = 0
elif fname_lower.startswith("china-s"):
ordering = 1
elif fname_lower.startswith("korea"):
ordering = 3
elif fname_lower.startswith("japan"):
ordering = 2
elif fname_lower in fitz_fontdescriptors.keys():
import pymupdf_fonts # optional fonts
fontbuffer = pymupdf_fonts.myfont(fname_lower) # make a copy
fontname = None # ensure using fontbuffer only
del pymupdf_fonts # remove package again
elif ordering < 0:
fontname = Base14_fontdict.get(fontname, fontname)
lang = mupdf.fz_text_language_from_string(language)
font = JM_get_font(fontname, fontfile,
fontbuffer, script, lang, ordering,
is_bold, is_italic, is_serif, embed)
self.this = font
def __repr__(self):
return "Font('%s')" % self.name
@property
def ascender(self):
"""Return the glyph ascender value."""
return mupdf.fz_font_ascender(self.this)
@property
def bbox(self):
return self.this.fz_font_bbox()
@property
def buffer(self):
buffer_ = mupdf.FzBuffer( mupdf.ll_fz_keep_buffer( self.this.m_internal.buffer))
return mupdf.fz_buffer_extract_copy( buffer_)
def char_lengths(self, text, fontsize=11, language=None, script=0, wmode=0, small_caps=0):
"""Return tuple of char lengths of unicode 'text' under a fontsize."""
lang = mupdf.fz_text_language_from_string(language)
rc = []
for ch in text:
c = ord(ch)
if small_caps:
gid = mupdf.fz_encode_character_sc(self.this, c)
if gid >= 0:
font = self.this
else:
gid, font = mupdf.fz_encode_character_with_fallback(self.this, c, script, lang)
rc.append(fontsize * mupdf.fz_advance_glyph(font, gid, wmode))
return rc
@property
def descender(self):
"""Return the glyph descender value."""
return mupdf.fz_font_descender(self.this)
@property
def flags(self):
f = mupdf.ll_fz_font_flags(self.this.m_internal)
if not f:
return
assert isinstance( f, mupdf.fz_font_flags_t)
#log( '{=f}')
if mupdf_cppyy:
# cppyy includes remaining higher bits.
v = [f.is_mono]
def b(bits):
ret = v[0] & ((1 << bits)-1)
v[0] = v[0] >> bits
return ret
is_mono = b(1)
is_serif = b(1)
is_bold = b(1)
is_italic = b(1)
ft_substitute = b(1)
ft_stretch = b(1)
fake_bold = b(1)
fake_italic = b(1)
has_opentype = b(1)
invalid_bbox = b(1)
cjk_lang = b(1)
embed = b(1)
never_embed = b(1)
return {
"mono": is_mono if mupdf_cppyy else f.is_mono,
"serif": is_serif if mupdf_cppyy else f.is_serif,
"bold": is_bold if mupdf_cppyy else f.is_bold,
"italic": is_italic if mupdf_cppyy else f.is_italic,
"substitute": ft_substitute if mupdf_cppyy else f.ft_substitute,
"stretch": ft_stretch if mupdf_cppyy else f.ft_stretch,
"fake-bold": fake_bold if mupdf_cppyy else f.fake_bold,
"fake-italic": fake_italic if mupdf_cppyy else f.fake_italic,
"opentype": has_opentype if mupdf_cppyy else f.has_opentype,
"invalid-bbox": invalid_bbox if mupdf_cppyy else f.invalid_bbox,
'cjk': cjk_lang if mupdf_cppyy else f.cjk,
'cjk-lang': cjk_lang if mupdf_cppyy else f.cjk_lang,
'embed': embed if mupdf_cppyy else f.embed,
'never-embed': never_embed if mupdf_cppyy else f.never_embed,
}
def glyph_advance(self, chr_, language=None, script=0, wmode=0, small_caps=0):
"""Return the glyph width of a unicode (font size 1)."""
lang = mupdf.fz_text_language_from_string(language)
if small_caps:
gid = mupdf.fz_encode_character_sc(self.this, chr_)
if gid >= 0:
font = self.this
else:
gid, font = mupdf.fz_encode_character_with_fallback(self.this, chr_, script, lang)
return mupdf.fz_advance_glyph(font, gid, wmode)
def glyph_bbox(self, char, language=None, script=0, small_caps=0):
"""Return the glyph bbox of a unicode (font size 1)."""
lang = mupdf.fz_text_language_from_string(language)
if small_caps:
gid = mupdf.fz_encode_character_sc( self.this, char)
if gid >= 0:
font = self.this
else:
gid, font = mupdf.fz_encode_character_with_fallback( self.this, char, script, lang)
return Rect(mupdf.fz_bound_glyph( font, gid, mupdf.FzMatrix()))
@property
def glyph_count(self):
return self.this.m_internal.glyph_count
def glyph_name_to_unicode(self, name):
"""Return the unicode for a glyph name."""
return glyph_name_to_unicode(name)
def has_glyph(self, chr, language=None, script=0, fallback=0, small_caps=0):
"""Check whether font has a glyph for this unicode."""
if fallback:
lang = mupdf.fz_text_language_from_string(language)
gid, font = mupdf.fz_encode_character_with_fallback(self.this, chr, script, lang)
else:
if small_caps:
gid = mupdf.fz_encode_character_sc(self.this, chr)
else:
gid = mupdf.fz_encode_character(self.this, chr)
return gid
@property
def is_bold(self):
return mupdf.fz_font_is_bold( self.this)
@property
def is_italic(self):
return mupdf.fz_font_is_italic( self.this)
@property
def is_monospaced(self):
return mupdf.fz_font_is_monospaced( self.this)
@property
def is_serif(self):
return mupdf.fz_font_is_serif( self.this)
@property
def is_writable(self):
return True # see pymupdf commit ef4056ee4da2
font = self.this
flags = mupdf.ll_fz_font_flags(font.m_internal)
if mupdf_cppyy:
# cppyy doesn't handle bitfields correctly.
import cppyy
ft_substitute = cppyy.gbl.mupdf_mfz_font_flags_ft_substitute( flags)
else:
ft_substitute = flags.ft_substitute
if ( mupdf.ll_fz_font_t3_procs(font.m_internal)
or ft_substitute
or not mupdf.pdf_font_writing_supported(font)
):
return False
return True
@property
def name(self):
ret = mupdf.fz_font_name(self.this)
#log( '{ret=}')
return ret
def text_length(self, text, fontsize=11, language=None, script=0, wmode=0, small_caps=0):
"""Return length of unicode 'text' under a fontsize."""
thisfont = self.this
lang = mupdf.fz_text_language_from_string(language)
rc = 0
if not isinstance(text, str):
raise TypeError( MSG_BAD_TEXT)
for ch in text:
c = ord(ch)
if small_caps:
gid = mupdf.fz_encode_character_sc(thisfont, c)
if gid >= 0:
font = thisfont
else:
gid, font = mupdf.fz_encode_character_with_fallback(thisfont, c, script, lang)
rc += mupdf.fz_advance_glyph(font, gid, wmode)
rc *= fontsize
return rc
def unicode_to_glyph_name(self, ch):
"""Return the glyph name for a unicode."""
return unicode_to_glyph_name(ch)
def valid_codepoints(self):
'''
Returns sorted list of valid unicodes of a fz_font.
'''
if mupdf_version_tuple < (1, 25):
# mupdf.fz_enumerate_font_cmap2() not available.
return []
ucs_gids = mupdf.fz_enumerate_font_cmap2(self.this)
ucss = [i.ucs for i in ucs_gids]
ucss_unique = set(ucss)
ucss_unique_sorted = sorted(ucss_unique)
return ucss_unique_sorted
class Graftmap:
def __del__(self):
if not type(self) is Graftmap:
return
self.thisown = False
def __init__(self, doc):
dst = _as_pdf_document(doc)
map_ = mupdf.pdf_new_graft_map(dst)
self.this = map_
self.thisown = True
class Link:
def __del__(self):
self._erase()
def __init__( self, this):
assert isinstance( this, mupdf.FzLink)
self.this = this
def __repr__(self):
CheckParent(self)
return "link on " + str(self.parent)
def __str__(self):
CheckParent(self)
return "link on " + str(self.parent)
def _border(self, doc, xref):
pdf = _as_pdf_document(doc, required=0)
if not pdf.m_internal:
return
link_obj = mupdf.pdf_new_indirect(pdf, xref, 0)
if not link_obj.m_internal:
return
b = JM_annot_border(link_obj)
return b
def _colors(self, doc, xref):
pdf = _as_pdf_document(doc, required=0)
if not pdf.m_internal:
return
link_obj = mupdf.pdf_new_indirect( pdf, xref, 0)
if not link_obj.m_internal:
raise ValueError( MSG_BAD_XREF)
b = JM_annot_colors( link_obj)
return b
def _erase(self):
self.parent = None
self.thisown = False
def _setBorder(self, border, doc, xref):
pdf = _as_pdf_document(doc, required=0)
if not pdf.m_internal:
return
link_obj = mupdf.pdf_new_indirect(pdf, xref, 0)
if not link_obj.m_internal:
return
b = JM_annot_set_border(border, pdf, link_obj)
return b
@property
def border(self):
return self._border(self.parent.parent.this, self.xref)
@property
def colors(self):
return self._colors(self.parent.parent.this, self.xref)
@property
def dest(self):
"""Create link destination details."""
if hasattr(self, "parent") and self.parent is None:
raise ValueError("orphaned object: parent is None")
if self.parent.parent.is_closed or self.parent.parent.is_encrypted:
raise ValueError("document closed or encrypted")
doc = self.parent.parent
if self.is_external or self.uri.startswith("#"):
uri = None
else:
uri = doc.resolve_link(self.uri)
return linkDest(self, uri, doc)
@property
def flags(self)->int:
CheckParent(self)
doc = self.parent.parent
if not doc.is_pdf:
return 0
f = doc.xref_get_key(self.xref, "F")
if f[1] != "null":
return int(f[1])
return 0
@property
def is_external(self):
"""Flag the link as external."""
CheckParent(self)
if g_use_extra:
return extra.Link_is_external( self.this)
this_link = self.this
if not this_link.m_internal or not this_link.m_internal.uri:
return False
return bool( mupdf.fz_is_external_link( this_link.m_internal.uri))
@property
def next(self):
"""Next link."""
if not self.this.m_internal:
return None
CheckParent(self)
if 0 and g_use_extra:
val = extra.Link_next( self.this)
else:
val = self.this.next()
if not val.m_internal:
return None
val = Link( val)
if val:
val.thisown = True
val.parent = self.parent # copy owning page from prev link
val.parent._annot_refs[id(val)] = val
if self.xref > 0: # prev link has an xref
link_xrefs = [x[0] for x in self.parent.annot_xrefs() if x[1] == mupdf.PDF_ANNOT_LINK]
link_ids = [x[2] for x in self.parent.annot_xrefs() if x[1] == mupdf.PDF_ANNOT_LINK]
idx = link_xrefs.index(self.xref)
val.xref = link_xrefs[idx + 1]
val.id = link_ids[idx + 1]
else:
val.xref = 0
val.id = ""
return val
@property
def rect(self):
"""Rectangle ('hot area')."""
CheckParent(self)
# utils.py:getLinkDict() appears to expect exceptions from us, so we
# ensure that we raise on error.
if self.this is None or not self.this.m_internal:
raise Exception( 'self.this.m_internal not available')
val = JM_py_from_rect( self.this.rect())
val = Rect(val)
return val
def set_border(self, border=None, width=0, dashes=None, style=None):
if type(border) is not dict:
border = {"width": width, "style": style, "dashes": dashes}
return self._setBorder(border, self.parent.parent.this, self.xref)
def set_colors(self, colors=None, stroke=None, fill=None):
"""Set border colors."""
CheckParent(self)
doc = self.parent.parent
if type(colors) is not dict:
colors = {"fill": fill, "stroke": stroke}
fill = colors.get("fill")
stroke = colors.get("stroke")
if fill is not None:
message("warning: links have no fill color")
if stroke in ([], ()):
doc.xref_set_key(self.xref, "C", "[]")
return
if hasattr(stroke, "__float__"):
stroke = [float(stroke)]
CheckColor(stroke)
assert len(stroke) in (1, 3, 4)
s = f"[{_format_g(stroke)}]"
doc.xref_set_key(self.xref, "C", s)
def set_flags(self, flags):
CheckParent(self)
doc = self.parent.parent
if not doc.is_pdf:
raise ValueError("is no PDF")
if not type(flags) is int:
raise ValueError("bad 'flags' value")
doc.xref_set_key(self.xref, "F", str(flags))
return None
@property
def uri(self):
"""Uri string."""
#CheckParent(self)
if g_use_extra:
return extra.link_uri(self.this)
this_link = self.this
return this_link.m_internal.uri if this_link.m_internal else ''
page = -1
class Matrix:
def __abs__(self):
return math.sqrt(sum([c*c for c in self]))
def __add__(self, m):
if hasattr(m, "__float__"):
return Matrix(self.a + m, self.b + m, self.c + m,
self.d + m, self.e + m, self.f + m)
if len(m) != 6:
raise ValueError("Matrix: bad seq len")
return Matrix(self.a + m[0], self.b + m[1], self.c + m[2],
self.d + m[3], self.e + m[4], self.f + m[5])
def __bool__(self):
return not (max(self) == min(self) == 0)
def __eq__(self, mat):
if not hasattr(mat, "__len__"):
return False
return len(mat) == 6 and bool(self - mat) is False
def __getitem__(self, i):
return (self.a, self.b, self.c, self.d, self.e, self.f)[i]
def __init__(self, *args, a=None, b=None, c=None, d=None, e=None, f=None):
"""
Matrix() - all zeros
Matrix(a, b, c, d, e, f)
Matrix(zoom-x, zoom-y) - zoom
Matrix(shear-x, shear-y, 1) - shear
Matrix(degree) - rotate
Matrix(Matrix) - new copy
Matrix(sequence) - from 'sequence'
Matrix(mupdf.FzMatrix) - from MuPDF class wrapper for fz_matrix.
Explicit keyword args a, b, c, d, e, f override any earlier settings if
not None.
"""
if not args:
self.a = self.b = self.c = self.d = self.e = self.f = 0.0
elif len(args) > 6:
raise ValueError("Matrix: bad seq len")
elif len(args) == 6: # 6 numbers
self.a, self.b, self.c, self.d, self.e, self.f = map(float, args)
elif len(args) == 1: # either an angle or a sequ
if isinstance(args[0], mupdf.FzMatrix):
self.a = args[0].a
self.b = args[0].b
self.c = args[0].c
self.d = args[0].d
self.e = args[0].e
self.f = args[0].f
elif hasattr(args[0], "__float__"):
theta = math.radians(args[0])
c_ = round(math.cos(theta), 8)
s_ = round(math.sin(theta), 8)
self.a = self.d = c_
self.b = s_
self.c = -s_
self.e = self.f = 0.0
else:
self.a, self.b, self.c, self.d, self.e, self.f = map(float, args[0])
elif len(args) == 2 or len(args) == 3 and args[2] == 0:
self.a, self.b, self.c, self.d, self.e, self.f = float(args[0]), \
0.0, 0.0, float(args[1]), 0.0, 0.0
elif len(args) == 3 and args[2] == 1:
self.a, self.b, self.c, self.d, self.e, self.f = 1.0, \
float(args[1]), float(args[0]), 1.0, 0.0, 0.0
else:
raise ValueError("Matrix: bad args")
# Override with explicit args if specified.
if a is not None: self.a = a
if b is not None: self.b = b
if c is not None: self.c = c
if d is not None: self.d = d
if e is not None: self.e = e
if f is not None: self.f = f
def __invert__(self):
"""Calculate inverted matrix."""
m1 = Matrix()
m1.invert(self)
return m1
def __len__(self):
return 6
def __mul__(self, m):
if hasattr(m, "__float__"):
return Matrix(self.a * m, self.b * m, self.c * m,
self.d * m, self.e * m, self.f * m)
m1 = Matrix(1,1)
return m1.concat(self, m)
def __neg__(self):
return Matrix(-self.a, -self.b, -self.c, -self.d, -self.e, -self.f)
def __nonzero__(self):
return not (max(self) == min(self) == 0)
def __pos__(self):
return Matrix(self)
def __repr__(self):
return "Matrix" + str(tuple(self))
def __setitem__(self, i, v):
v = float(v)
if i == 0: self.a = v
elif i == 1: self.b = v
elif i == 2: self.c = v
elif i == 3: self.d = v
elif i == 4: self.e = v
elif i == 5: self.f = v
else:
raise IndexError("index out of range")
return
def __sub__(self, m):
if hasattr(m, "__float__"):
return Matrix(self.a - m, self.b - m, self.c - m,
self.d - m, self.e - m, self.f - m)
if len(m) != 6:
raise ValueError("Matrix: bad seq len")
return Matrix(self.a - m[0], self.b - m[1], self.c - m[2],
self.d - m[3], self.e - m[4], self.f - m[5])
def __truediv__(self, m):
if hasattr(m, "__float__"):
return Matrix(self.a * 1./m, self.b * 1./m, self.c * 1./m,
self.d * 1./m, self.e * 1./m, self.f * 1./m)
m1 = util_invert_matrix(m)[1]
if not m1:
raise ZeroDivisionError("matrix not invertible")
m2 = Matrix(1,1)
return m2.concat(self, m1)
def concat(self, one, two):
"""Multiply two matrices and replace current one."""
if not len(one) == len(two) == 6:
raise ValueError("Matrix: bad seq len")
self.a, self.b, self.c, self.d, self.e, self.f = util_concat_matrix(one, two)
return self
def invert(self, src=None):
"""Calculate the inverted matrix. Return 0 if successful and replace
current one. Else return 1 and do nothing.
"""
if src is None:
dst = util_invert_matrix(self)
else:
dst = util_invert_matrix(src)
if dst[0] == 1:
return 1
self.a, self.b, self.c, self.d, self.e, self.f = dst[1]
return 0
@property
def is_rectilinear(self):
"""True if rectangles are mapped to rectangles."""
return (abs(self.b) < EPSILON and abs(self.c) < EPSILON) or \
(abs(self.a) < EPSILON and abs(self.d) < EPSILON)
def prerotate(self, theta):
"""Calculate pre rotation and replace current matrix."""
theta = float(theta)
while theta < 0: theta += 360
while theta >= 360: theta -= 360
if abs(0 - theta) < EPSILON:
pass
elif abs(90.0 - theta) < EPSILON:
a = self.a
b = self.b
self.a = self.c
self.b = self.d
self.c = -a
self.d = -b
elif abs(180.0 - theta) < EPSILON:
self.a = -self.a
self.b = -self.b
self.c = -self.c
self.d = -self.d
elif abs(270.0 - theta) < EPSILON:
a = self.a
b = self.b
self.a = -self.c
self.b = -self.d
self.c = a
self.d = b
else:
rad = math.radians(theta)
s = math.sin(rad)
c = math.cos(rad)
a = self.a
b = self.b
self.a = c * a + s * self.c
self.b = c * b + s * self.d
self.c =-s * a + c * self.c
self.d =-s * b + c * self.d
return self
def prescale(self, sx, sy):
"""Calculate pre scaling and replace current matrix."""
sx = float(sx)
sy = float(sy)
self.a *= sx
self.b *= sx
self.c *= sy
self.d *= sy
return self
def preshear(self, h, v):
"""Calculate pre shearing and replace current matrix."""
h = float(h)
v = float(v)
a, b = self.a, self.b
self.a += v * self.c
self.b += v * self.d
self.c += h * a
self.d += h * b
return self
def pretranslate(self, tx, ty):
"""Calculate pre translation and replace current matrix."""
tx = float(tx)
ty = float(ty)
self.e += tx * self.a + ty * self.c
self.f += tx * self.b + ty * self.d
return self
__inv__ = __invert__
__div__ = __truediv__
norm = __abs__
class IdentityMatrix(Matrix):
"""Identity matrix [1, 0, 0, 1, 0, 0]"""
def __hash__(self):
return hash((1,0,0,1,0,0))
def __init__(self):
Matrix.__init__(self, 1.0, 1.0)
def __repr__(self):
return "IdentityMatrix(1.0, 0.0, 0.0, 1.0, 0.0, 0.0)"
def __setattr__(self, name, value):
if name in "ad":
self.__dict__[name] = 1.0
elif name in "bcef":
self.__dict__[name] = 0.0
else:
self.__dict__[name] = value
def checkargs(*args):
raise NotImplementedError("Identity is readonly")
Identity = IdentityMatrix()
class linkDest:
"""link or outline destination details"""
def __init__(self, obj, rlink, document=None):
isExt = obj.is_external
isInt = not isExt
self.dest = ""
self.file_spec = ""
self.flags = 0
self.is_map = False
self.is_uri = False
self.kind = LINK_NONE
self.lt = Point(0, 0)
self.named = dict()
self.new_window = ""
self.page = obj.page
self.rb = Point(0, 0)
self.uri = obj.uri
def uri_to_dict(uri):
items = self.uri[1:].split('&')
ret = dict()
for item in items:
eq = item.find('=')
if eq >= 0:
ret[item[:eq]] = item[eq+1:]
else:
ret[item] = None
return ret
def unescape(name):
"""Unescape '%AB' substrings to chr(0xAB)."""
split = name.replace("%%", "%25") # take care of escaped '%'
split = split.split("%")
newname = split[0]
for item in split[1:]:
piece = item[:2]
newname += chr(int(piece, base=16))
newname += item[2:]
return newname
if rlink and not self.uri.startswith("#"):
self.uri = f"#page={rlink[0] + 1}&zoom=0,{_format_g(rlink[1])},{_format_g(rlink[2])}"
if obj.is_external:
self.page = -1
self.kind = LINK_URI
if not self.uri:
self.page = -1
self.kind = LINK_NONE
if isInt and self.uri:
self.uri = self.uri.replace("&zoom=nan", "&zoom=0")
if self.uri.startswith("#"):
self.kind = LINK_GOTO
m = re.match('^#page=([0-9]+)&zoom=([0-9.]+),(-?[0-9.]+),(-?[0-9.]+)$', self.uri)
if m:
self.page = int(m.group(1)) - 1
self.lt = Point(float((m.group(3))), float(m.group(4)))
self.flags = self.flags | LINK_FLAG_L_VALID | LINK_FLAG_T_VALID
else:
m = re.match('^#page=([0-9]+)$', self.uri)
if m:
self.page = int(m.group(1)) - 1
else:
self.kind = LINK_NAMED
m = re.match('^#nameddest=(.*)', self.uri)
assert document
if document and m:
named = unescape(m.group(1))
self.named = document.resolve_names().get(named)
if self.named is None:
# document.resolve_names() does not contain an
# entry for `named` so use an empty dict.
self.named = dict()
self.named['nameddest'] = named
else:
self.named = uri_to_dict(self.uri[1:])
else:
self.kind = LINK_NAMED
self.named = uri_to_dict(self.uri)
if obj.is_external:
if not self.uri:
pass
elif self.uri.startswith("file:"):
self.file_spec = self.uri[5:]
if self.file_spec.startswith("//"):
self.file_spec = self.file_spec[2:]
self.is_uri = False
self.uri = ""
self.kind = LINK_LAUNCH
ftab = self.file_spec.split("#")
if len(ftab) == 2:
if ftab[1].startswith("page="):
self.kind = LINK_GOTOR
self.file_spec = ftab[0]
self.page = int(ftab[1].split("&")[0][5:]) - 1
elif ":" in self.uri:
self.is_uri = True
self.kind = LINK_URI
else:
self.is_uri = True
self.kind = LINK_LAUNCH
assert isinstance(self.named, dict)
class Widget:
'''
Class describing a PDF form field ("widget")
'''
def __init__(self):
self.border_color = None
self.border_style = "S"
self.border_width = 0
self.border_dashes = None
self.choice_values = None # choice fields only
self.rb_parent = None # radio buttons only: xref of owning parent
self.field_name = None # field name
self.field_label = None # field label
self.field_value = None
self.field_flags = 0
self.field_display = 0
self.field_type = 0 # valid range 1 through 7
self.field_type_string = None # field type as string
self.fill_color = None
self.button_caption = None # button caption
self.is_signed = None # True / False if signature
self.text_color = (0, 0, 0)
self.text_font = "Helv"
self.text_fontsize = 0
self.text_maxlen = 0 # text fields only
self.text_format = 0 # text fields only
self._text_da = "" # /DA = default appearance
self.script = None # JavaScript (/A)
self.script_stroke = None # JavaScript (/AA/K)
self.script_format = None # JavaScript (/AA/F)
self.script_change = None # JavaScript (/AA/V)
self.script_calc = None # JavaScript (/AA/C)
self.script_blur = None # JavaScript (/AA/Bl)
self.script_focus = None # JavaScript (/AA/Fo) codespell:ignore
self.rect = None # annot value
self.xref = 0 # annot value
def __repr__(self):
#return "'%s' widget on %s" % (self.field_type_string, str(self.parent))
# No self.parent.
return f'Widget:(field_type={self.field_type_string} script={self.script})'
return "'%s' widget" % (self.field_type_string)
def _adjust_font(self):
"""Ensure text_font is from our list and correctly spelled.
"""
if not self.text_font:
self.text_font = "Helv"
return
valid_fonts = ("Cour", "TiRo", "Helv", "ZaDb")
for f in valid_fonts:
if self.text_font.lower() == f.lower():
self.text_font = f
return
self.text_font = "Helv"
return
def _checker(self):
"""Any widget type checks.
"""
if self.field_type not in range(1, 8):
raise ValueError("bad field type")
# if setting a radio button to ON, first set Off all buttons
# in the group - this is not done by MuPDF:
if self.field_type == mupdf.PDF_WIDGET_TYPE_RADIOBUTTON and self.field_value not in (False, "Off") and hasattr(self, "parent"):
# so we are about setting this button to ON/True
# check other buttons in same group and set them to 'Off'
doc = self.parent.parent
kids_type, kids_value = doc.xref_get_key(self.xref, "Parent/Kids")
if kids_type == "array":
xrefs = tuple(map(int, kids_value[1:-1].replace("0 R","").split()))
for xref in xrefs:
if xref != self.xref:
doc.xref_set_key(xref, "AS", "/Off")
# the calling method will now set the intended button to on and
# will find everything prepared for correct functioning.
def _parse_da(self):
"""Extract font name, size and color from default appearance string (/DA object).
Equivalent to 'pdf_parse_default_appearance' function in MuPDF's 'pdf-annot.c'.
"""
if not self._text_da:
return
font = "Helv"
fsize = 0
col = (0, 0, 0)
dat = self._text_da.split() # split on any whitespace
for i, item in enumerate(dat):
if item == "Tf":
font = dat[i - 2][1:]
fsize = float(dat[i - 1])
dat[i] = dat[i-1] = dat[i-2] = ""
continue
if item == "g": # unicolor text
col = [(float(dat[i - 1]))]
dat[i] = dat[i-1] = ""
continue
if item == "rg": # RGB colored text
col = [float(f) for f in dat[i - 3:i]]
dat[i] = dat[i-1] = dat[i-2] = dat[i-3] = ""
continue
self.text_font = font
self.text_fontsize = fsize
self.text_color = col
self._text_da = ""
return
def _validate(self):
"""Validate the class entries.
"""
if (self.rect.is_infinite
or self.rect.is_empty
):
raise ValueError("bad rect")
if not self.field_name:
raise ValueError("field name missing")
if self.field_label == "Unnamed":
self.field_label = None
CheckColor(self.border_color)
CheckColor(self.fill_color)
if not self.text_color:
self.text_color = (0, 0, 0)
CheckColor(self.text_color)
if not self.border_width:
self.border_width = 0
if not self.text_fontsize:
self.text_fontsize = 0
self.border_style = self.border_style.upper()[0:1]
# standardize content of JavaScript entries
btn_type = self.field_type in (
mupdf.PDF_WIDGET_TYPE_BUTTON,
mupdf.PDF_WIDGET_TYPE_CHECKBOX,
mupdf.PDF_WIDGET_TYPE_RADIOBUTTON,
)
if not self.script:
self.script = None
elif type(self.script) is not str:
raise ValueError("script content must be a string")
# buttons cannot have the following script actions
if btn_type or not self.script_calc:
self.script_calc = None
elif type(self.script_calc) is not str:
raise ValueError("script_calc content must be a string")
if btn_type or not self.script_change:
self.script_change = None
elif type(self.script_change) is not str:
raise ValueError("script_change content must be a string")
if btn_type or not self.script_format:
self.script_format = None
elif type(self.script_format) is not str:
raise ValueError("script_format content must be a string")
if btn_type or not self.script_stroke:
self.script_stroke = None
elif type(self.script_stroke) is not str:
raise ValueError("script_stroke content must be a string")
if btn_type or not self.script_blur:
self.script_blur = None
elif type(self.script_blur) is not str:
raise ValueError("script_blur content must be a string")
if btn_type or not self.script_focus:
self.script_focus = None
elif type(self.script_focus) is not str:
raise ValueError("script_focus content must be a string")
self._checker() # any field_type specific checks
def button_states(self):
"""Return the on/off state names for button widgets.
A button may have 'normal' or 'pressed down' appearances. While the 'Off'
state is usually called like this, the 'On' state is often given a name
relating to the functional context.
"""
if self.field_type not in (2, 5):
return None # no button type
if hasattr(self, "parent"): # field already exists on page
doc = self.parent.parent
else:
return
xref = self.xref
states = {"normal": None, "down": None}
APN = doc.xref_get_key(xref, "AP/N")
if APN[0] == "dict":
nstates = []
APN = APN[1][2:-2]
apnt = APN.split("/")[1:]
for x in apnt:
nstates.append(x.split()[0])
states["normal"] = nstates
if APN[0] == "xref":
nstates = []
nxref = int(APN[1].split(" ")[0])
APN = doc.xref_object(nxref)
apnt = APN.split("/")[1:]
for x in apnt:
nstates.append(x.split()[0])
states["normal"] = nstates
APD = doc.xref_get_key(xref, "AP/D")
if APD[0] == "dict":
dstates = []
APD = APD[1][2:-2]
apdt = APD.split("/")[1:]
for x in apdt:
dstates.append(x.split()[0])
states["down"] = dstates
if APD[0] == "xref":
dstates = []
dxref = int(APD[1].split(" ")[0])
APD = doc.xref_object(dxref)
apdt = APD.split("/")[1:]
for x in apdt:
dstates.append(x.split()[0])
states["down"] = dstates
return states
@property
def next(self):
return self._annot.next
def on_state(self):
"""Return the "On" value for button widgets.
This is useful for radio buttons mainly. Checkboxes will always return
"Yes". Radio buttons will return the string that is unequal to "Off"
as returned by method button_states().
If the radio button is new / being created, it does not yet have an
"On" value. In this case, a warning is shown and True is returned.
"""
if self.field_type not in (2, 5):
return None # no checkbox or radio button
if self.field_type == 2:
return "Yes"
bstate = self.button_states()
if bstate is None:
bstate = dict()
for k in bstate.keys():
for v in bstate[k]:
if v != "Off":
return v
message("warning: radio button has no 'On' value.")
return True
def reset(self):
"""Reset the field value to its default.
"""
TOOLS._reset_widget(self._annot)
def update(self):
"""Reflect Python object in the PDF.
"""
self._validate()
self._adjust_font() # ensure valid text_font name
# now create the /DA string
self._text_da = ""
if len(self.text_color) == 3:
fmt = "{:g} {:g} {:g} rg /{f:s} {s:g} Tf" + self._text_da
elif len(self.text_color) == 1:
fmt = "{:g} g /{f:s} {s:g} Tf" + self._text_da
elif len(self.text_color) == 4:
fmt = "{:g} {:g} {:g} {:g} k /{f:s} {s:g} Tf" + self._text_da
self._text_da = fmt.format(*self.text_color, f=self.text_font,
s=self.text_fontsize)
# finally update the widget
# if widget has a '/AA/C' script, make sure it is in the '/CO'
# array of the '/AcroForm' dictionary.
if self.script_calc: # there is a "calculation" script:
# make sure we are in the /CO array
util_ensure_widget_calc(self._annot)
# finally update the widget
TOOLS._save_widget(self._annot, self)
self._text_da = ""
from . import _extra
class Outline:
def __init__(self, ol):
self.this = ol
@property
def dest(self):
'''outline destination details'''
return linkDest(self, None, None)
def destination(self, document):
'''
Like `dest` property but uses `document` to resolve destinations for
kind=LINK_NAMED.
'''
return linkDest(self, None, document)
@property
def down(self):
ol = self.this
down_ol = ol.down()
if not down_ol.m_internal:
return
return Outline(down_ol)
@property
def is_external(self):
if g_use_extra:
# calling _extra.* here appears to save significant time in
# test_toc.py:test_full_toc, 1.2s=>0.94s.
#
return _extra.Outline_is_external( self.this)
ol = self.this
if not ol.m_internal:
return False
uri = ol.m_internal.uri if 1 else ol.uri()
if uri is None:
return False
return mupdf.fz_is_external_link(uri)
@property
def is_open(self):
if 1:
return self.this.m_internal.is_open
return self.this.is_open()
@property
def next(self):
ol = self.this
next_ol = ol.next()
if not next_ol.m_internal:
return
return Outline(next_ol)
@property
def page(self):
if 1:
return self.this.m_internal.page.page
return self.this.page().page
@property
def title(self):
return self.this.m_internal.title
@property
def uri(self):
ol = self.this
if not ol.m_internal:
return None
return ol.m_internal.uri
@property
def x(self):
return self.this.m_internal.x
@property
def y(self):
return self.this.m_internal.y
__slots__ = [ 'this']
def _make_PdfFilterOptions(
recurse=0,
instance_forms=0,
ascii=0,
no_update=0,
sanitize=0,
sopts=None,
):
'''
Returns a mupdf.PdfFilterOptions instance.
'''
filter_ = mupdf.PdfFilterOptions()
filter_.recurse = recurse
filter_.instance_forms = instance_forms
filter_.ascii = ascii
filter_.no_update = no_update
if sanitize:
# We want to use a PdfFilterFactory whose `.filter` fn pointer is
# set to MuPDF's `pdf_new_sanitize_filter()`. But not sure how to
# get access to this raw fn in Python; and on Windows raw MuPDF
# functions are not even available to C++.
#
# So we use SWIG Director to implement our own
# PdfFilterFactory whose `filter()` method calls
# `mupdf.ll_pdf_new_sanitize_filter()`.
if sopts:
assert isinstance(sopts, mupdf.PdfSanitizeFilterOptions)
else:
sopts = mupdf.PdfSanitizeFilterOptions()
class Factory(mupdf.PdfFilterFactory2):
def __init__(self):
super().__init__()
self.use_virtual_filter()
self.sopts = sopts
def filter(self, ctx, doc, chain, struct_parents, transform, options):
if 0:
log(f'sanitize filter.filter():')
log(f' {self=}')
log(f' {ctx=}')
log(f' {doc=}')
log(f' {chain=}')
log(f' {struct_parents=}')
log(f' {transform=}')
log(f' {options=}')
log(f' {self.sopts.internal()=}')
return mupdf.ll_pdf_new_sanitize_filter(
doc,
chain,
struct_parents,
transform,
options,
self.sopts.internal(),
)
factory = Factory()
filter_.add_factory(factory.internal())
filter_._factory = factory
return filter_
class Page:
def __init__(self, page, document):
assert isinstance(page, (mupdf.FzPage, mupdf.PdfPage)), f'page is: {page}'
self.this = page
self.thisown = True
self.last_point = None
self.draw_cont = ''
self._annot_refs = dict()
self.parent = document
if page.m_internal:
if isinstance( page, mupdf.PdfPage):
self.number = page.m_internal.super.number
else:
self.number = page.m_internal.number
else:
self.number = None
def __repr__(self):
return self.__str__()
CheckParent(self)
x = self.parent.name
if self.parent.stream is not None:
x = "<memory, doc# %i>" % (self.parent._graft_id,)
if x == "":
x = "<new PDF, doc# %i>" % self.parent._graft_id
return "page %s of %s" % (self.number, x)
def __str__(self):
#CheckParent(self)
parent = getattr(self, 'parent', None)
if isinstance(self.this.m_internal, mupdf.pdf_page):
number = self.this.m_internal.super.number
else:
number = self.this.m_internal.number
ret = f'page {number}'
if parent:
x = self.parent.name
if self.parent.stream is not None:
x = "<memory, doc# %i>" % (self.parent._graft_id,)
if x == "":
x = "<new PDF, doc# %i>" % self.parent._graft_id
ret += f' of {x}'
return ret
def _add_caret_annot(self, point):
if g_use_extra:
annot = extra._add_caret_annot( self.this, JM_point_from_py(point))
else:
page = self._pdf_page()
annot = mupdf.pdf_create_annot(page, mupdf.PDF_ANNOT_CARET)
if point:
p = JM_point_from_py(point)
r = mupdf.pdf_annot_rect(annot)
r = mupdf.FzRect(p.x, p.y, p.x + r.x1 - r.x0, p.y + r.y1 - r.y0)
mupdf.pdf_set_annot_rect(annot, r)
mupdf.pdf_update_annot(annot)
JM_add_annot_id(annot, "A")
return annot
def _add_file_annot(self, point, buffer_, filename, ufilename=None, desc=None, icon=None):
page = self._pdf_page()
uf = ufilename if ufilename else filename
d = desc if desc else filename
p = JM_point_from_py(point)
filebuf = JM_BufferFromBytes(buffer_)
if not filebuf.m_internal:
raise TypeError( MSG_BAD_BUFFER)
annot = mupdf.pdf_create_annot(page, mupdf.PDF_ANNOT_FILE_ATTACHMENT)
r = mupdf.pdf_annot_rect(annot)
r = mupdf.fz_make_rect(p.x, p.y, p.x + r.x1 - r.x0, p.y + r.y1 - r.y0)
mupdf.pdf_set_annot_rect(annot, r)
flags = mupdf.PDF_ANNOT_IS_PRINT
mupdf.pdf_set_annot_flags(annot, flags)
if icon:
mupdf.pdf_set_annot_icon_name(annot, icon)
val = JM_embed_file(page.doc(), filebuf, filename, uf, d, 1)
mupdf.pdf_dict_put(mupdf.pdf_annot_obj(annot), PDF_NAME('FS'), val)
mupdf.pdf_dict_put_text_string(mupdf.pdf_annot_obj(annot), PDF_NAME('Contents'), filename)
mupdf.pdf_update_annot(annot)
mupdf.pdf_set_annot_rect(annot, r)
mupdf.pdf_set_annot_flags(annot, flags)
JM_add_annot_id(annot, "A")
return Annot(annot)
def _add_freetext_annot(
self, rect,
text,
fontsize=11,
fontname=None,
text_color=None,
fill_color=None,
border_color=None,
align=0,
rotate=0,
):
page = self._pdf_page()
nfcol, fcol = JM_color_FromSequence(fill_color)
ntcol, tcol = JM_color_FromSequence(text_color)
r = JM_rect_from_py(rect)
if mupdf.fz_is_infinite_rect(r) or mupdf.fz_is_empty_rect(r):
raise ValueError( MSG_BAD_RECT)
annot = mupdf.pdf_create_annot( page, mupdf.PDF_ANNOT_FREE_TEXT)
annot_obj = mupdf.pdf_annot_obj( annot)
mupdf.pdf_set_annot_contents( annot, text)
mupdf.pdf_set_annot_rect( annot, r)
mupdf.pdf_dict_put_int( annot_obj, PDF_NAME('Rotate'), rotate)
mupdf.pdf_dict_put_int( annot_obj, PDF_NAME('Q'), align)
if nfcol > 0:
mupdf.pdf_set_annot_color( annot, fcol[:nfcol])
# insert the default appearance string
JM_make_annot_DA(annot, ntcol, tcol, fontname, fontsize)
mupdf.pdf_update_annot( annot)
JM_add_annot_id(annot, "A")
val = Annot(annot)
#%pythonappend _add_freetext_annot
ap = val._getAP()
BT = ap.find(b"BT")
ET = ap.rfind(b"ET") + 2
ap = ap[BT:ET]
w = rect[2]-rect[0]
h = rect[3]-rect[1]
if rotate in (90, -90, 270):
w, h = h, w
re = f"0 0 {_format_g((w, h))} re".encode()
ap = re + b"\nW\nn\n" + ap
ope = None
bwidth = b""
fill_string = ColorCode(fill_color, "f").encode()
if fill_string:
fill_string += b"\n"
ope = b"f"
stroke_string = ColorCode(border_color, "c").encode()
if stroke_string:
stroke_string += b"\n"
bwidth = b"1 w\n"
ope = b"S"
if fill_string and stroke_string:
ope = b"B"
if ope is not None:
ap = bwidth + fill_string + stroke_string + re + b"\n" + ope + b"\n" + ap
val._setAP(ap)
return val
def _add_ink_annot(self, list):
page = _as_pdf_page(self.this)
if not PySequence_Check(list):
raise ValueError( MSG_BAD_ARG_INK_ANNOT)
ctm = mupdf.FzMatrix()
mupdf.pdf_page_transform(page, mupdf.FzRect(0), ctm)
inv_ctm = mupdf.fz_invert_matrix(ctm)
annot = mupdf.pdf_create_annot(page, mupdf.PDF_ANNOT_INK)
annot_obj = mupdf.pdf_annot_obj(annot)
n0 = len(list)
inklist = mupdf.pdf_new_array(page.doc(), n0)
for j in range(n0):
sublist = list[j]
n1 = len(sublist)
stroke = mupdf.pdf_new_array(page.doc(), 2 * n1)
for i in range(n1):
p = sublist[i]
if not PySequence_Check(p) or PySequence_Size(p) != 2:
raise ValueError( MSG_BAD_ARG_INK_ANNOT)
point = mupdf.fz_transform_point(JM_point_from_py(p), inv_ctm)
mupdf.pdf_array_push_real(stroke, point.x)
mupdf.pdf_array_push_real(stroke, point.y)
mupdf.pdf_array_push(inklist, stroke)
mupdf.pdf_dict_put(annot_obj, PDF_NAME('InkList'), inklist)
mupdf.pdf_update_annot(annot)
JM_add_annot_id(annot, "A")
return Annot(annot)
def _add_line_annot(self, p1, p2):
page = self._pdf_page()
annot = mupdf.pdf_create_annot(page, mupdf.PDF_ANNOT_LINE)
a = JM_point_from_py(p1)
b = JM_point_from_py(p2)
mupdf.pdf_set_annot_line(annot, a, b)
mupdf.pdf_update_annot(annot)
JM_add_annot_id(annot, "A")
assert annot.m_internal
return Annot(annot)
def _add_multiline(self, points, annot_type):
page = self._pdf_page()
if len(points) < 2:
raise ValueError( MSG_BAD_ARG_POINTS)
annot = mupdf.pdf_create_annot(page, annot_type)
for p in points:
if (PySequence_Size(p) != 2):
raise ValueError( MSG_BAD_ARG_POINTS)
point = JM_point_from_py(p)
mupdf.pdf_add_annot_vertex(annot, point)
mupdf.pdf_update_annot(annot)
JM_add_annot_id(annot, "A")
return Annot(annot)
def _add_redact_annot(self, quad, text=None, da_str=None, align=0, fill=None, text_color=None):
page = self._pdf_page()
fcol = [ 1, 1, 1, 0]
nfcol = 0
annot = mupdf.pdf_create_annot(page, mupdf.PDF_ANNOT_REDACT)
q = JM_quad_from_py(quad)
r = mupdf.fz_rect_from_quad(q)
# TODO calculate de-rotated rect
mupdf.pdf_set_annot_rect(annot, r)
if fill:
nfcol, fcol = JM_color_FromSequence(fill)
arr = mupdf.pdf_new_array(page.doc(), nfcol)
for i in range(nfcol):
mupdf.pdf_array_push_real(arr, fcol[i])
mupdf.pdf_dict_put(mupdf.pdf_annot_obj(annot), PDF_NAME('IC'), arr)
if text:
mupdf.pdf_dict_puts(
mupdf.pdf_annot_obj(annot),
"OverlayText",
mupdf.pdf_new_text_string(text),
)
mupdf.pdf_dict_put_text_string(mupdf.pdf_annot_obj(annot), PDF_NAME('DA'), da_str)
mupdf.pdf_dict_put_int(mupdf.pdf_annot_obj(annot), PDF_NAME('Q'), align)
mupdf.pdf_update_annot(annot)
JM_add_annot_id(annot, "A")
annot = mupdf.ll_pdf_keep_annot(annot.m_internal)
annot = mupdf.PdfAnnot( annot)
return Annot(annot)
def _add_square_or_circle(self, rect, annot_type):
page = self._pdf_page()
r = JM_rect_from_py(rect)
if mupdf.fz_is_infinite_rect(r) or mupdf.fz_is_empty_rect(r):
raise ValueError( MSG_BAD_RECT)
annot = mupdf.pdf_create_annot(page, annot_type)
mupdf.pdf_set_annot_rect(annot, r)
mupdf.pdf_update_annot(annot)
JM_add_annot_id(annot, "A")
assert annot.m_internal
return Annot(annot)
def _add_stamp_annot(self, rect, stamp=0):
page = self._pdf_page()
stamp_id = [
PDF_NAME('Approved'),
PDF_NAME('AsIs'),
PDF_NAME('Confidential'),
PDF_NAME('Departmental'),
PDF_NAME('Experimental'),
PDF_NAME('Expired'),
PDF_NAME('Final'),
PDF_NAME('ForComment'),
PDF_NAME('ForPublicRelease'),
PDF_NAME('NotApproved'),
PDF_NAME('NotForPublicRelease'),
PDF_NAME('Sold'),
PDF_NAME('TopSecret'),
PDF_NAME('Draft'),
]
n = len(stamp_id)
name = stamp_id[0]
r = JM_rect_from_py(rect)
if mupdf.fz_is_infinite_rect(r) or mupdf.fz_is_empty_rect(r):
raise ValueError( MSG_BAD_RECT)
if _INRANGE(stamp, 0, n-1):
name = stamp_id[stamp]
annot = mupdf.pdf_create_annot(page, mupdf.PDF_ANNOT_STAMP)
mupdf.pdf_set_annot_rect(annot, r)
try:
n = PDF_NAME('Name')
mupdf.pdf_dict_put(mupdf.pdf_annot_obj(annot), PDF_NAME('Name'), name)
except Exception:
if g_exceptions_verbose: exception_info()
raise
mupdf.pdf_set_annot_contents(
annot,
mupdf.pdf_dict_get_name(mupdf.pdf_annot_obj(annot), PDF_NAME('Name')),
)
mupdf.pdf_update_annot(annot)
JM_add_annot_id(annot, "A")
return Annot(annot)
def _add_text_annot(self, point, text, icon=None):
page = self._pdf_page()
p = JM_point_from_py( point)
annot = mupdf.pdf_create_annot(page, mupdf.PDF_ANNOT_TEXT)
r = mupdf.pdf_annot_rect(annot)
r = mupdf.fz_make_rect(p.x, p.y, p.x + r.x1 - r.x0, p.y + r.y1 - r.y0)
mupdf.pdf_set_annot_rect(annot, r)
mupdf.pdf_set_annot_contents(annot, text)
if icon:
mupdf.pdf_set_annot_icon_name(annot, icon)
mupdf.pdf_update_annot(annot)
JM_add_annot_id(annot, "A")
return Annot(annot)
def _add_text_marker(self, quads, annot_type):
CheckParent(self)
if not self.parent.is_pdf:
raise ValueError("is no PDF")
val = Page__add_text_marker(self, quads, annot_type)
if not val:
return None
val.parent = weakref.proxy(self)
self._annot_refs[id(val)] = val
return val
def _addAnnot_FromString(self, linklist):
"""Add links from list of object sources."""
CheckParent(self)
if g_use_extra:
self.__class__._addAnnot_FromString = extra.Page_addAnnot_FromString
#log('Page._addAnnot_FromString() deferring to extra.Page_addAnnot_FromString().')
return extra.Page_addAnnot_FromString( self.this, linklist)
page = _as_pdf_page(self.this)
lcount = len(linklist) # link count
if lcount < 1:
return
i = -1
# insert links from the provided sources
if not isinstance(linklist, tuple):
raise ValueError( "bad 'linklist' argument")
if not mupdf.pdf_dict_get( page.obj(), PDF_NAME('Annots')).m_internal:
mupdf.pdf_dict_put_array( page.obj(), PDF_NAME('Annots'), lcount)
annots = mupdf.pdf_dict_get( page.obj(), PDF_NAME('Annots'))
assert annots.m_internal, f'{lcount=} {annots.m_internal=}'
for i in range(lcount):
txtpy = linklist[i]
text = JM_StrAsChar(txtpy)
if not text:
message("skipping bad link / annot item %i.", i)
continue
try:
annot = mupdf.pdf_add_object( page.doc(), JM_pdf_obj_from_str( page.doc(), text))
ind_obj = mupdf.pdf_new_indirect( page.doc(), mupdf.pdf_to_num( annot), 0)
mupdf.pdf_array_push( annots, ind_obj)
except Exception:
if g_exceptions_verbose: exception_info()
message("skipping bad link / annot item %i.\n" % i)
def _addWidget(self, field_type, field_name):
page = self._pdf_page()
pdf = page.doc()
annot = JM_create_widget(pdf, page, field_type, field_name)
if not annot.m_internal:
raise RuntimeError( "cannot create widget")
JM_add_annot_id(annot, "W")
return Annot(annot)
def _apply_redactions(self, text, images, graphics):
page = self._pdf_page()
opts = mupdf.PdfRedactOptions()
opts.black_boxes = 0 # no black boxes
opts.text = text # how to treat text
opts.image_method = images # how to treat images
opts.line_art = graphics # how to treat vector graphics
success = mupdf.pdf_redact_page(page.doc(), page, opts)
return success
def _erase(self):
self._reset_annot_refs()
try:
self.parent._forget_page(self)
except Exception:
exception_info()
pass
self.parent = None
self.thisown = False
self.number = None
self.this = None
def _count_q_balance(self):
"""Count missing graphic state pushs and pops.
Returns:
A pair of integers (push, pop). Push is the number of missing
PDF "q" commands, pop is the number of "Q" commands.
A balanced graphics state for the page will be reached if its
/Contents is prepended with 'push' copies of string "q\n"
and appended with 'pop' copies of "\nQ".
"""
page = _as_pdf_page(self) # need the underlying PDF page
res = mupdf.pdf_dict_get( # access /Resources
page.obj(),
mupdf.PDF_ENUM_NAME_Resources,
)
cont = mupdf.pdf_dict_get( # access /Contents
page.obj(),
mupdf.PDF_ENUM_NAME_Contents,
)
pdf = _as_pdf_document(self.parent) # need underlying PDF document
# return value of MuPDF function
return mupdf.pdf_count_q_balance_outparams_fn(pdf, res, cont)
def _get_optional_content(self, oc: OptInt) -> OptStr:
if oc is None or oc == 0:
return None
doc = self.parent
check = doc.xref_object(oc, compressed=True)
if not ("/Type/OCG" in check or "/Type/OCMD" in check):
#log( 'raising "bad optional content"')
raise ValueError("bad optional content: 'oc'")
#log( 'Looking at self._get_resource_properties()')
props = {}
for p, x in self._get_resource_properties():
props[x] = p
if oc in props.keys():
return props[oc]
i = 0
mc = "MC%i" % i
while mc in props.values():
i += 1
mc = "MC%i" % i
self._set_resource_property(mc, oc)
#log( 'returning {mc=}')
return mc
def _get_resource_properties(self):
'''
page list Resource/Properties
'''
page = self._pdf_page()
rc = JM_get_resource_properties(page.obj())
return rc
def _get_textpage(self, clip=None, flags=0, matrix=None):
if g_use_extra:
ll_tpage = extra.page_get_textpage(self.this, clip, flags, matrix)
tpage = mupdf.FzStextPage(ll_tpage)
return tpage
page = self.this
options = mupdf.FzStextOptions(flags)
rect = JM_rect_from_py(clip)
# Default to page's rect if `clip` not specified, for #2048.
rect = mupdf.fz_bound_page(page) if clip is None else JM_rect_from_py(clip)
ctm = JM_matrix_from_py(matrix)
tpage = mupdf.FzStextPage(rect)
dev = mupdf.fz_new_stext_device(tpage, options)
if _globals.no_device_caching:
mupdf.fz_enable_device_hints( dev, mupdf.FZ_NO_CACHE)
if isinstance(page, mupdf.FzPage):
pass
elif isinstance(page, mupdf.PdfPage):
page = page.super()
else:
assert 0, f'Unrecognised {type(page)=}'
mupdf.fz_run_page(page, dev, ctm, mupdf.FzCookie())
mupdf.fz_close_device(dev)
return tpage
def _insert_image(self,
filename=None, pixmap=None, stream=None, imask=None, clip=None,
overlay=1, rotate=0, keep_proportion=1, oc=0, width=0, height=0,
xref=0, alpha=-1, _imgname=None, digests=None
):
maskbuf = mupdf.FzBuffer()
page = self._pdf_page()
# This will create an empty PdfDocument with a call to
# pdf_new_document() then assign page.doc()'s return value to it (which
# drop the original empty pdf_document).
pdf = page.doc()
w = width
h = height
img_xref = xref
rc_digest = 0
do_process_pixmap = 1
do_process_stream = 1
do_have_imask = 1
do_have_image = 1
do_have_xref = 1
if xref > 0:
ref = mupdf.pdf_new_indirect(pdf, xref, 0)
w = mupdf.pdf_to_int( mupdf.pdf_dict_geta( ref, PDF_NAME('Width'), PDF_NAME('W')))
h = mupdf.pdf_to_int( mupdf.pdf_dict_geta( ref, PDF_NAME('Height'), PDF_NAME('H')))
if w + h == 0:
raise ValueError( MSG_IS_NO_IMAGE)
#goto have_xref()
do_process_pixmap = 0
do_process_stream = 0
do_have_imask = 0
do_have_image = 0
else:
if stream:
imgbuf = JM_BufferFromBytes(stream)
do_process_pixmap = 0
else:
if filename:
imgbuf = mupdf.fz_read_file(filename)
#goto have_stream()
do_process_pixmap = 0
if do_process_pixmap:
#log( 'do_process_pixmap')
# process pixmap ---------------------------------
arg_pix = pixmap.this
w = arg_pix.w()
h = arg_pix.h()
digest = mupdf.fz_md5_pixmap2(arg_pix)
md5_py = digest
temp = digests.get(md5_py, None)
if temp is not None:
img_xref = temp
ref = mupdf.pdf_new_indirect(page.doc(), img_xref, 0)
#goto have_xref()
do_process_stream = 0
do_have_imask = 0
do_have_image = 0
else:
if arg_pix.alpha() == 0:
image = mupdf.fz_new_image_from_pixmap(arg_pix, mupdf.FzImage())
else:
pm = mupdf.fz_convert_pixmap(
arg_pix,
mupdf.FzColorspace(),
mupdf.FzColorspace(),
mupdf.FzDefaultColorspaces(None),
mupdf.FzColorParams(),
1,
)
pm.alpha = 0
pm.colorspace = None
mask = mupdf.fz_new_image_from_pixmap(pm, mupdf.FzImage())
image = mupdf.fz_new_image_from_pixmap(arg_pix, mask)
#goto have_image()
do_process_stream = 0
do_have_imask = 0
if do_process_stream:
#log( 'do_process_stream')
# process stream ---------------------------------
state = mupdf.FzMd5()
if mupdf_cppyy:
mupdf.fz_md5_update_buffer( state, imgbuf)
else:
mupdf.fz_md5_update(state, imgbuf.m_internal.data, imgbuf.m_internal.len)
if imask:
maskbuf = JM_BufferFromBytes(imask)
if mupdf_cppyy:
mupdf.fz_md5_update_buffer( state, maskbuf)
else:
mupdf.fz_md5_update(state, maskbuf.m_internal.data, maskbuf.m_internal.len)
digest = mupdf.fz_md5_final2(state)
md5_py = bytes(digest)
temp = digests.get(md5_py, None)
if temp is not None:
img_xref = temp
ref = mupdf.pdf_new_indirect(page.doc(), img_xref, 0)
w = mupdf.pdf_to_int( mupdf.pdf_dict_geta( ref, PDF_NAME('Width'), PDF_NAME('W')))
h = mupdf.pdf_to_int( mupdf.pdf_dict_geta( ref, PDF_NAME('Height'), PDF_NAME('H')))
#goto have_xref()
do_have_imask = 0
do_have_image = 0
else:
image = mupdf.fz_new_image_from_buffer(imgbuf)
w = image.w()
h = image.h()
if not imask:
#goto have_image()
do_have_imask = 0
if do_have_imask:
if mupdf_version_tuple >= (1, 24):
# `fz_compressed_buffer` is reference counted and
# `mupdf.fz_new_image_from_compressed_buffer2()`
# is povided as a Swig-friendly wrapper for
# `fz_new_image_from_compressed_buffer()`, so we can do things
# straightfowardly.
#
cbuf1 = mupdf.fz_compressed_image_buffer( image)
if not cbuf1.m_internal:
raise ValueError( "uncompressed image cannot have mask")
bpc = image.bpc()
colorspace = image.colorspace()
xres, yres = mupdf.fz_image_resolution(image)
mask = mupdf.fz_new_image_from_buffer(maskbuf)
image = mupdf.fz_new_image_from_compressed_buffer2(
w,
h,
bpc,
colorspace,
xres,
yres,
1, # interpolate
0, # imagemask,
list(), # decode
list(), # colorkey
cbuf1,
mask,
)
else:
#log( 'do_have_imask')
# mupdf.FzCompressedBuffer is not copyable, so
# mupdf.fz_compressed_image_buffer() does not work - it cannot
# return by value. And sharing a fz_compressed_buffer between two
# `fz_image`'s doesn't work, so we use a raw fz_compressed_buffer
# here, not a mupdf.FzCompressedBuffer.
#
cbuf1 = mupdf.ll_fz_compressed_image_buffer( image.m_internal)
if not cbuf1:
raise ValueError( "uncompressed image cannot have mask")
bpc = image.bpc()
colorspace = image.colorspace()
xres, yres = mupdf.fz_image_resolution(image)
mask = mupdf.fz_new_image_from_buffer(maskbuf)
# mupdf.ll_fz_new_image_from_compressed_buffer() is not usable.
zimg = extra.fz_new_image_from_compressed_buffer(
w,
h,
bpc,
colorspace.m_internal,
xres,
yres,
1, # interpolate
0, # imagemask,
cbuf1,
mask.m_internal,
)
zimg = mupdf.FzImage(zimg)
# `image` and `zimage` both have pointers to the same
# `fz_compressed_buffer`, which is not reference counted, and they
# both think that they own it.
#
# So we do what the classic implementation does, and simply
# ensure that `fz_drop_image(image)` is never called. This will
# leak some of `image`'s allocations (for example the main
# `fz_image` allocation), but it's not trivial to avoid this.
#
# Perhaps we could manually set `fz_image`'s
# `fz_compressed_buffer*` to null? Trouble is we'd have to
# cast the `fz_image*` to a `fz_compressed_image*` to see the
# `fz_compressed_buffer*`, which is probably not possible from
# Python?
#
image.m_internal = None
image = zimg
if do_have_image:
#log( 'do_have_image')
ref = mupdf.pdf_add_image(pdf, image)
if oc:
JM_add_oc_object(pdf, ref, oc)
img_xref = mupdf.pdf_to_num(ref)
digests[md5_py] = img_xref
rc_digest = 1
if do_have_xref:
#log( 'do_have_xref')
resources = mupdf.pdf_dict_get_inheritable(page.obj(), PDF_NAME('Resources'))
if not resources.m_internal:
resources = mupdf.pdf_dict_put_dict(page.obj(), PDF_NAME('Resources'), 2)
xobject = mupdf.pdf_dict_get(resources, PDF_NAME('XObject'))
if not xobject.m_internal:
xobject = mupdf.pdf_dict_put_dict(resources, PDF_NAME('XObject'), 2)
mat = calc_image_matrix(w, h, clip, rotate, keep_proportion)
mupdf.pdf_dict_puts(xobject, _imgname, ref)
nres = mupdf.fz_new_buffer(50)
s = f"\nq\n{_format_g((mat.a, mat.b, mat.c, mat.d, mat.e, mat.f))} cm\n/{_imgname} Do\nQ\n"
#s = s.replace('\n', '\r\n')
mupdf.fz_append_string(nres, s)
JM_insert_contents(pdf, page.obj(), nres, overlay)
if rc_digest:
return img_xref, digests
else:
return img_xref, None
def _insertFont(self, fontname, bfname, fontfile, fontbuffer, set_simple, idx, wmode, serif, encoding, ordering):
page = self._pdf_page()
pdf = page.doc()
value = JM_insert_font(pdf, bfname, fontfile,fontbuffer, set_simple, idx, wmode, serif, encoding, ordering)
# get the objects /Resources, /Resources/Font
resources = mupdf.pdf_dict_get_inheritable( page.obj(), PDF_NAME('Resources'))
fonts = mupdf.pdf_dict_get(resources, PDF_NAME('Font'))
if not fonts.m_internal: # page has no fonts yet
fonts = mupdf.pdf_new_dict(pdf, 5)
mupdf.pdf_dict_putl(page.obj(), fonts, PDF_NAME('Resources'), PDF_NAME('Font'))
# store font in resources and fonts objects will contain named reference to font
_, xref = JM_INT_ITEM(value, 0)
if not xref:
raise RuntimeError( "cannot insert font")
font_obj = mupdf.pdf_new_indirect(pdf, xref, 0)
mupdf.pdf_dict_puts(fonts, fontname, font_obj)
return value
def _load_annot(self, name, xref):
page = self._pdf_page()
if xref == 0:
annot = JM_get_annot_by_name(page, name)
else:
annot = JM_get_annot_by_xref(page, xref)
if annot.m_internal:
return Annot(annot)
def _makePixmap(self, doc, ctm, cs, alpha=0, annots=1, clip=None):
pix = JM_pixmap_from_page(doc, self.this, ctm, cs, alpha, annots, clip)
return Pixmap(pix)
def _other_box(self, boxtype):
rect = mupdf.FzRect( mupdf.FzRect.Fixed_INFINITE)
page = _as_pdf_page(self.this, required=False)
if page.m_internal:
obj = mupdf.pdf_dict_gets( page.obj(), boxtype)
if mupdf.pdf_is_array(obj):
rect = mupdf.pdf_to_rect(obj)
if mupdf.fz_is_infinite_rect( rect):
return
return JM_py_from_rect(rect)
def _pdf_page(self, required=True):
return _as_pdf_page(self.this, required=required)
def _reset_annot_refs(self):
"""Invalidate / delete all annots of this page."""
self._annot_refs.clear()
def _set_opacity(self, gstate=None, CA=1, ca=1, blendmode=None):
if CA >= 1 and ca >= 1 and blendmode is None:
return
tCA = int(round(max(CA , 0) * 100))
if tCA >= 100:
tCA = 99
tca = int(round(max(ca, 0) * 100))
if tca >= 100:
tca = 99
gstate = "fitzca%02i%02i" % (tCA, tca)
if not gstate:
return
page = _as_pdf_page(self.this)
resources = mupdf.pdf_dict_get(page.obj(), PDF_NAME('Resources'))
if not resources.m_internal:
resources = mupdf.pdf_dict_put_dict(page.obj(), PDF_NAME('Resources'), 2)
extg = mupdf.pdf_dict_get(resources, PDF_NAME('ExtGState'))
if not extg.m_internal:
extg = mupdf.pdf_dict_put_dict(resources, PDF_NAME('ExtGState'), 2)
n = mupdf.pdf_dict_len(extg)
for i in range(n):
o1 = mupdf.pdf_dict_get_key(extg, i)
name = mupdf.pdf_to_name(o1)
if name == gstate:
return gstate
opa = mupdf.pdf_new_dict(page.doc(), 3)
mupdf.pdf_dict_put_real(opa, PDF_NAME('CA'), CA)
mupdf.pdf_dict_put_real(opa, PDF_NAME('ca'), ca)
mupdf.pdf_dict_puts(extg, gstate, opa)
return gstate
def _set_pagebox(self, boxtype, rect):
doc = self.parent
if doc is None:
raise ValueError("orphaned object: parent is None")
if not doc.is_pdf:
raise ValueError("is no PDF")
valid_boxes = ("CropBox", "BleedBox", "TrimBox", "ArtBox")
if boxtype not in valid_boxes:
raise ValueError("bad boxtype")
rect = Rect(rect)
mb = self.mediabox
rect = Rect(rect[0], mb.y1 - rect[3], rect[2], mb.y1 - rect[1])
if not (mb.x0 <= rect.x0 < rect.x1 <= mb.x1 and mb.y0 <= rect.y0 < rect.y1 <= mb.y1):
raise ValueError(f"{boxtype} not in MediaBox")
doc.xref_set_key(self.xref, boxtype, f"[{_format_g(tuple(rect))}]")
def _set_resource_property(self, name, xref):
page = self._pdf_page()
JM_set_resource_property(page.obj(), name, xref)
def _show_pdf_page(self, fz_srcpage, overlay=1, matrix=None, xref=0, oc=0, clip=None, graftmap=None, _imgname=None):
cropbox = JM_rect_from_py(clip)
mat = JM_matrix_from_py(matrix)
rc_xref = xref
tpage = _as_pdf_page(self.this)
tpageref = tpage.obj()
pdfout = tpage.doc() # target PDF
ENSURE_OPERATION(pdfout)
#-------------------------------------------------------------
# convert the source page to a Form XObject
#-------------------------------------------------------------
xobj1 = JM_xobject_from_page(pdfout, fz_srcpage, xref, graftmap.this)
if not rc_xref:
rc_xref = mupdf.pdf_to_num(xobj1)
#-------------------------------------------------------------
# create referencing XObject (controls display on target page)
#-------------------------------------------------------------
# fill reference to xobj1 into the /Resources
#-------------------------------------------------------------
subres1 = mupdf.pdf_new_dict(pdfout, 5)
mupdf.pdf_dict_puts(subres1, "fullpage", xobj1)
subres = mupdf.pdf_new_dict(pdfout, 5)
mupdf.pdf_dict_put(subres, PDF_NAME('XObject'), subres1)
res = mupdf.fz_new_buffer(20)
mupdf.fz_append_string(res, "/fullpage Do")
xobj2 = mupdf.pdf_new_xobject(pdfout, cropbox, mat, subres, res)
if oc > 0:
JM_add_oc_object(pdfout, mupdf.pdf_resolve_indirect(xobj2), oc)
#-------------------------------------------------------------
# update target page with xobj2:
#-------------------------------------------------------------
# 1. insert Xobject in Resources
#-------------------------------------------------------------
resources = mupdf.pdf_dict_get_inheritable(tpageref, PDF_NAME('Resources'))
subres = mupdf.pdf_dict_get(resources, PDF_NAME('XObject'))
if not subres.m_internal:
subres = mupdf.pdf_dict_put_dict(resources, PDF_NAME('XObject'), 5)
mupdf.pdf_dict_puts(subres, _imgname, xobj2)
#-------------------------------------------------------------
# 2. make and insert new Contents object
#-------------------------------------------------------------
nres = mupdf.fz_new_buffer(50) # buffer for Do-command
mupdf.fz_append_string(nres, " q /") # Do-command
mupdf.fz_append_string(nres, _imgname)
mupdf.fz_append_string(nres, " Do Q ")
JM_insert_contents(pdfout, tpageref, nres, overlay)
return rc_xref
def add_caret_annot(self, point: point_like) -> Annot:
"""Add a 'Caret' annotation."""
old_rotation = annot_preprocess(self)
try:
annot = self._add_caret_annot(point)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot = Annot( annot)
annot_postprocess(self, annot)
assert hasattr( annot, 'parent')
return annot
def add_circle_annot(self, rect: rect_like) -> Annot:
"""Add a 'Circle' (ellipse, oval) annotation."""
old_rotation = annot_preprocess(self)
try:
annot = self._add_square_or_circle(rect, mupdf.PDF_ANNOT_CIRCLE)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot_postprocess(self, annot)
return annot
def add_file_annot(
self,
point: point_like,
buffer_: typing.ByteString,
filename: str,
ufilename: OptStr =None,
desc: OptStr =None,
icon: OptStr =None
) -> Annot:
"""Add a 'FileAttachment' annotation."""
old_rotation = annot_preprocess(self)
try:
annot = self._add_file_annot(point,
buffer_,
filename,
ufilename=ufilename,
desc=desc,
icon=icon,
)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot_postprocess(self, annot)
return annot
def add_freetext_annot(
self,
rect: rect_like,
text: str,
fontsize: float =11,
fontname: OptStr =None,
border_color: OptSeq =None,
text_color: OptSeq =None,
fill_color: OptSeq =None,
align: int =0,
rotate: int =0
) -> Annot:
"""Add a 'FreeText' annotation."""
old_rotation = annot_preprocess(self)
try:
annot = self._add_freetext_annot(
rect,
text,
fontsize=fontsize,
fontname=fontname,
border_color=border_color,
text_color=text_color,
fill_color=fill_color,
align=align,
rotate=rotate,
)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot_postprocess(self, annot)
return annot
def add_highlight_annot(self, quads=None, start=None,
stop=None, clip=None) -> Annot:
"""Add a 'Highlight' annotation."""
if quads is None:
q = get_highlight_selection(self, start=start, stop=stop, clip=clip)
else:
q = CheckMarkerArg(quads)
ret = self._add_text_marker(q, mupdf.PDF_ANNOT_HIGHLIGHT)
return ret
def add_ink_annot(self, handwriting: list) -> Annot:
"""Add a 'Ink' ('handwriting') annotation.
The argument must be a list of lists of point_likes.
"""
old_rotation = annot_preprocess(self)
try:
annot = self._add_ink_annot(handwriting)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot_postprocess(self, annot)
return annot
def add_line_annot(self, p1: point_like, p2: point_like) -> Annot:
"""Add a 'Line' annotation."""
old_rotation = annot_preprocess(self)
try:
annot = self._add_line_annot(p1, p2)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot_postprocess(self, annot)
return annot
def add_polygon_annot(self, points: list) -> Annot:
"""Add a 'Polygon' annotation."""
old_rotation = annot_preprocess(self)
try:
annot = self._add_multiline(points, mupdf.PDF_ANNOT_POLYGON)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot_postprocess(self, annot)
return annot
def add_polyline_annot(self, points: list) -> Annot:
"""Add a 'PolyLine' annotation."""
old_rotation = annot_preprocess(self)
try:
annot = self._add_multiline(points, mupdf.PDF_ANNOT_POLY_LINE)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot_postprocess(self, annot)
return annot
def add_rect_annot(self, rect: rect_like) -> Annot:
"""Add a 'Square' (rectangle) annotation."""
old_rotation = annot_preprocess(self)
try:
annot = self._add_square_or_circle(rect, mupdf.PDF_ANNOT_SQUARE)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot_postprocess(self, annot)
return annot
def add_redact_annot(
self,
quad,
text: OptStr =None,
fontname: OptStr =None,
fontsize: float =11,
align: int =0,
fill: OptSeq =None,
text_color: OptSeq =None,
cross_out: bool =True,
) -> Annot:
"""Add a 'Redact' annotation."""
da_str = None
if text and not set(string.whitespace).issuperset(text):
CheckColor(fill)
CheckColor(text_color)
if not fontname:
fontname = "Helv"
if not fontsize:
fontsize = 11
if not text_color:
text_color = (0, 0, 0)
if hasattr(text_color, "__float__"):
text_color = (text_color, text_color, text_color)
if len(text_color) > 3:
text_color = text_color[:3]
fmt = "{:g} {:g} {:g} rg /{f:s} {s:g} Tf"
da_str = fmt.format(*text_color, f=fontname, s=fontsize)
if fill is None:
fill = (1, 1, 1)
if fill:
if hasattr(fill, "__float__"):
fill = (fill, fill, fill)
if len(fill) > 3:
fill = fill[:3]
old_rotation = annot_preprocess(self)
try:
annot = self._add_redact_annot(quad, text=text, da_str=da_str,
align=align, fill=fill)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot_postprocess(self, annot)
#-------------------------------------------------------------
# change appearance to show a crossed-out rectangle
#-------------------------------------------------------------
if cross_out:
ap_tab = annot._getAP().splitlines()[:-1] # get the 4 commands only
_, LL, LR, UR, UL = ap_tab
ap_tab.append(LR)
ap_tab.append(LL)
ap_tab.append(UR)
ap_tab.append(LL)
ap_tab.append(UL)
ap_tab.append(b"S")
ap = b"\n".join(ap_tab)
annot._setAP(ap, 0)
return annot
def add_squiggly_annot(
self,
quads=None,
start=None,
stop=None,
clip=None,
) -> Annot:
"""Add a 'Squiggly' annotation."""
if quads is None:
q = get_highlight_selection(self, start=start, stop=stop, clip=clip)
else:
q = CheckMarkerArg(quads)
return self._add_text_marker(q, mupdf.PDF_ANNOT_SQUIGGLY)
def add_stamp_annot(self, rect: rect_like, stamp: int =0) -> Annot:
"""Add a ('rubber') 'Stamp' annotation."""
old_rotation = annot_preprocess(self)
try:
annot = self._add_stamp_annot(rect, stamp)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot_postprocess(self, annot)
return annot
def add_strikeout_annot(self, quads=None, start=None, stop=None, clip=None) -> Annot:
"""Add a 'StrikeOut' annotation."""
if quads is None:
q = get_highlight_selection(self, start=start, stop=stop, clip=clip)
else:
q = CheckMarkerArg(quads)
return self._add_text_marker(q, mupdf.PDF_ANNOT_STRIKE_OUT)
def add_text_annot(self, point: point_like, text: str, icon: str ="Note") -> Annot:
"""Add a 'Text' (sticky note) annotation."""
old_rotation = annot_preprocess(self)
try:
annot = self._add_text_annot(point, text, icon=icon)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
annot_postprocess(self, annot)
return annot
def add_underline_annot(self, quads=None, start=None, stop=None, clip=None) -> Annot:
"""Add a 'Underline' annotation."""
if quads is None:
q = get_highlight_selection(self, start=start, stop=stop, clip=clip)
else:
q = CheckMarkerArg(quads)
return self._add_text_marker(q, mupdf.PDF_ANNOT_UNDERLINE)
def add_widget(self, widget: Widget) -> Annot:
"""Add a 'Widget' (form field)."""
CheckParent(self)
doc = self.parent
if not doc.is_pdf:
raise ValueError("is no PDF")
widget._validate()
annot = self._addWidget(widget.field_type, widget.field_name)
if not annot:
return None
annot.thisown = True
annot.parent = weakref.proxy(self) # owning page object
self._annot_refs[id(annot)] = annot
widget.parent = annot.parent
widget._annot = annot
widget.update()
return annot
def annot_names(self):
'''
page get list of annot names
'''
"""List of names of annotations, fields and links."""
CheckParent(self)
page = self._pdf_page(required=False)
if not page.m_internal:
return []
return JM_get_annot_id_list(page)
def annot_xrefs(self):
'''
List of xref numbers of annotations, fields and links.
'''
return JM_get_annot_xref_list2(self)
def annots(self, types=None):
""" Generator over the annotations of a page.
Args:
types: (list) annotation types to subselect from. If none,
all annotations are returned. E.g. types=[PDF_ANNOT_LINE]
will only yield line annotations.
"""
skip_types = (mupdf.PDF_ANNOT_LINK, mupdf.PDF_ANNOT_POPUP, mupdf.PDF_ANNOT_WIDGET)
if not hasattr(types, "__getitem__"):
annot_xrefs = [a[0] for a in self.annot_xrefs() if a[1] not in skip_types]
else:
annot_xrefs = [a[0] for a in self.annot_xrefs() if a[1] in types and a[1] not in skip_types]
for xref in annot_xrefs:
annot = self.load_annot(xref)
annot._yielded=True
yield annot
@property
def artbox(self):
"""The ArtBox"""
rect = self._other_box("ArtBox")
if rect is None:
return self.cropbox
mb = self.mediabox
return Rect(rect[0], mb.y1 - rect[3], rect[2], mb.y1 - rect[1])
@property
def bleedbox(self):
"""The BleedBox"""
rect = self._other_box("BleedBox")
if rect is None:
return self.cropbox
mb = self.mediabox
return Rect(rect[0], mb.y1 - rect[3], rect[2], mb.y1 - rect[1])
def bound(self):
"""Get page rectangle."""
CheckParent(self)
page = _as_fz_page(self.this)
val = mupdf.fz_bound_page(page)
val = Rect(val)
if val.is_infinite and self.parent.is_pdf:
cb = self.cropbox
w, h = cb.width, cb.height
if self.rotation not in (0, 180):
w, h = h, w
val = Rect(0, 0, w, h)
msg = TOOLS.mupdf_warnings(reset=False).splitlines()[-1]
message(msg)
return val
def clean_contents(self, sanitize=1):
if not sanitize and not self.is_wrapped:
self.wrap_contents()
page = _as_pdf_page( self.this, required=False)
if not page.m_internal:
return
filter_ = _make_PdfFilterOptions(recurse=1, sanitize=sanitize)
mupdf.pdf_filter_page_contents( page.doc(), page, filter_)
@property
def cropbox(self):
"""The CropBox."""
CheckParent(self)
page = self._pdf_page(required=False)
if not page.m_internal:
val = mupdf.fz_bound_page(self.this)
else:
val = JM_cropbox(page.obj())
val = Rect(val)
return val
@property
def cropbox_position(self):
return self.cropbox.tl
def delete_annot(self, annot):
"""Delete annot and return next one."""
CheckParent(self)
CheckParent(annot)
page = self._pdf_page()
while 1:
# first loop through all /IRT annots and remove them
irt_annot = JM_find_annot_irt(annot.this)
if not irt_annot: # no more there
break
mupdf.pdf_delete_annot(page, irt_annot.this)
nextannot = mupdf.pdf_next_annot(annot.this) # store next
mupdf.pdf_delete_annot(page, annot.this)
val = Annot(nextannot)
if val:
val.thisown = True
val.parent = weakref.proxy(self) # owning page object
val.parent._annot_refs[id(val)] = val
annot._erase()
return val
def delete_link(self, linkdict):
"""Delete a Link."""
CheckParent(self)
if not isinstance( linkdict, dict):
return # have no dictionary
def finished():
if linkdict["xref"] == 0: return
try:
linkid = linkdict["id"]
linkobj = self._annot_refs[linkid]
linkobj._erase()
except Exception:
# Don't print this exception, to match classic. Issue #2841.
if g_exceptions_verbose > 1: exception_info()
pass
page = _as_pdf_page(self.this, required=False)
if not page.m_internal:
return finished() # have no PDF
xref = linkdict[dictkey_xref]
if xref < 1:
return finished() # invalid xref
annots = mupdf.pdf_dict_get( page.obj(), PDF_NAME('Annots'))
if not annots.m_internal:
return finished() # have no annotations
len_ = mupdf.pdf_array_len( annots)
if len_ == 0:
return finished()
oxref = 0
for i in range( len_):
oxref = mupdf.pdf_to_num( mupdf.pdf_array_get( annots, i))
if xref == oxref:
break # found xref in annotations
if xref != oxref:
return finished() # xref not in annotations
mupdf.pdf_array_delete( annots, i) # delete entry in annotations
mupdf.pdf_delete_object( page.doc(), xref) # delete link object
mupdf.pdf_dict_put( page.obj(), PDF_NAME('Annots'), annots)
JM_refresh_links( page)
return finished()
@property
def derotation_matrix(self) -> Matrix:
"""Reflects page de-rotation."""
if g_use_extra:
return Matrix(extra.Page_derotate_matrix( self.this))
pdfpage = self._pdf_page(required=False)
if not pdfpage.m_internal:
return Matrix(mupdf.FzRect(mupdf.FzRect.UNIT))
return Matrix(JM_derotate_page_matrix(pdfpage))
def extend_textpage(self, tpage, flags=0, matrix=None):
page = self.this
tp = tpage.this
assert isinstance( tp, mupdf.FzStextPage)
options = mupdf.FzStextOptions()
options.flags = flags
ctm = JM_matrix_from_py(matrix)
dev = mupdf.FzDevice(tp, options)
mupdf.fz_run_page( page, dev, ctm, mupdf.FzCookie())
mupdf.fz_close_device( dev)
@property
def first_annot(self):
"""First annotation."""
CheckParent(self)
page = self._pdf_page(required=False)
if not page.m_internal:
return
annot = mupdf.pdf_first_annot(page)
if not annot.m_internal:
return
val = Annot(annot)
val.thisown = True
val.parent = weakref.proxy(self) # owning page object
self._annot_refs[id(val)] = val
return val
@property
def first_link(self):
'''
First link on page
'''
return self.load_links()
@property
def first_widget(self):
"""First widget/field."""
CheckParent(self)
annot = 0
page = self._pdf_page(required=False)
if not page.m_internal:
return
annot = mupdf.pdf_first_widget(page)
if not annot.m_internal:
return
val = Annot(annot)
val.thisown = True
val.parent = weakref.proxy(self) # owning page object
self._annot_refs[id(val)] = val
widget = Widget()
TOOLS._fill_widget(val, widget)
val = widget
return val
def get_bboxlog(self, layers=None):
CheckParent(self)
old_rotation = self.rotation
if old_rotation != 0:
self.set_rotation(0)
page = self.this
rc = []
inc_layers = True if layers else False
dev = JM_new_bbox_device( rc, inc_layers)
mupdf.fz_run_page( page, dev, mupdf.FzMatrix(), mupdf.FzCookie())
mupdf.fz_close_device( dev)
if old_rotation != 0:
self.set_rotation(old_rotation)
return rc
def get_cdrawings(self, extended=None, callback=None, method=None):
"""Extract vector graphics ("line art") from the page."""
CheckParent(self)
old_rotation = self.rotation
if old_rotation != 0:
self.set_rotation(0)
page = self.this
if isinstance(page, mupdf.PdfPage):
# Downcast pdf_page to fz_page.
page = mupdf.FzPage(page)
assert isinstance(page, mupdf.FzPage), f'{self.this=}'
clips = True if extended else False
prect = mupdf.fz_bound_page(page)
if g_use_extra:
rc = extra.get_cdrawings(page, extended, callback, method)
else:
rc = list()
if callable(callback) or method is not None:
dev = JM_new_lineart_device_Device(callback, clips, method)
else:
dev = JM_new_lineart_device_Device(rc, clips, method)
dev.ptm = mupdf.FzMatrix(1, 0, 0, -1, 0, prect.y1)
mupdf.fz_run_page(page, dev, mupdf.FzMatrix(), mupdf.FzCookie())
mupdf.fz_close_device(dev)
if old_rotation != 0:
self.set_rotation(old_rotation)
if callable(callback) or method is not None:
return
return rc
def get_contents(self):
"""Get xrefs of /Contents objects."""
CheckParent(self)
ret = []
page = _as_pdf_page(self.this)
obj = page.obj()
contents = mupdf.pdf_dict_get(obj, mupdf.PDF_ENUM_NAME_Contents)
if mupdf.pdf_is_array(contents):
n = mupdf.pdf_array_len(contents)
for i in range(n):
icont = mupdf.pdf_array_get(contents, i)
xref = mupdf.pdf_to_num(icont)
ret.append(xref)
elif contents.m_internal:
xref = mupdf.pdf_to_num(contents)
ret.append( xref)
return ret
def get_displaylist(self, annots=1):
'''
Make a DisplayList from the page for Pixmap generation.
Include (default) or exclude annotations.
'''
CheckParent(self)
if annots:
dl = mupdf.fz_new_display_list_from_page(self.this)
else:
dl = mupdf.fz_new_display_list_from_page_contents(self.this)
return DisplayList(dl)
def get_drawings(self, extended: bool=False) -> list:
"""Retrieve vector graphics. The extended version includes clips.
Note:
For greater comfort, this method converts point-likes, rect-likes, quad-likes
of the C version to respective Point / Rect / Quad objects.
It also adds default items that are missing in original path types.
"""
allkeys = (
'closePath',
'fill',
'color',
'width',
'lineCap',
'lineJoin',
'dashes',
'stroke_opacity',
'fill_opacity',
'even_odd',
)
val = self.get_cdrawings(extended=extended)
for i in range(len(val)):
npath = val[i]
if not npath["type"].startswith("clip"):
npath["rect"] = Rect(npath["rect"])
else:
npath["scissor"] = Rect(npath["scissor"])
if npath["type"]!="group":
items = npath["items"]
newitems = []
for item in items:
cmd = item[0]
rest = item[1:]
if cmd == "re":
item = ("re", Rect(rest[0]).normalize(), rest[1])
elif cmd == "qu":
item = ("qu", Quad(rest[0]))
else:
item = tuple([cmd] + [Point(i) for i in rest])
newitems.append(item)
npath["items"] = newitems
if npath['type'] in ('f', 's'):
for k in allkeys:
npath[k] = npath.get(k)
val[i] = npath
return val
class Drawpath(object):
"""Reflects a path dictionary from get_cdrawings()."""
def __init__(self, **args):
self.__dict__.update(args)
class Drawpathlist(object):
"""List of Path objects representing get_cdrawings() output."""
def __getitem__(self, item):
return self.paths.__getitem__(item)
def __init__(self):
self.paths = []
self.path_count = 0
self.group_count = 0
self.clip_count = 0
self.fill_count = 0
self.stroke_count = 0
self.fillstroke_count = 0
def __len__(self):
return self.paths.__len__()
def append(self, path):
self.paths.append(path)
self.path_count += 1
if path.type == "clip":
self.clip_count += 1
elif path.type == "group":
self.group_count += 1
elif path.type == "f":
self.fill_count += 1
elif path.type == "s":
self.stroke_count += 1
elif path.type == "fs":
self.fillstroke_count += 1
def clip_parents(self, i):
"""Return list of parent clip paths.
Args:
i: (int) return parents of this path.
Returns:
List of the clip parents."""
if i >= self.path_count:
raise IndexError("bad path index")
while i < 0:
i += self.path_count
lvl = self.paths[i].level
clips = list( # clip paths before identified one
reversed(
[
p
for p in self.paths[:i]
if p.type == "clip" and p.level < lvl
]
)
)
if clips == []: # none found: empty list
return []
nclips = [clips[0]] # init return list
for p in clips[1:]:
if p.level >= nclips[-1].level:
continue # only accept smaller clip levels
nclips.append(p)
return nclips
def group_parents(self, i):
"""Return list of parent group paths.
Args:
i: (int) return parents of this path.
Returns:
List of the group parents."""
if i >= self.path_count:
raise IndexError("bad path index")
while i < 0:
i += self.path_count
lvl = self.paths[i].level
groups = list( # group paths before identified one
reversed(
[
p
for p in self.paths[:i]
if p.type == "group" and p.level < lvl
]
)
)
if groups == []: # none found: empty list
return []
ngroups = [groups[0]] # init return list
for p in groups[1:]:
if p.level >= ngroups[-1].level:
continue # only accept smaller group levels
ngroups.append(p)
return ngroups
def get_lineart(self) -> object:
"""Get page drawings paths.
Note:
For greater comfort, this method converts point-like, rect-like, quad-like
tuples of the C version to respective Point / Rect / Quad objects.
Also adds default items that are missing in original path types.
In contrast to get_drawings(), this output is an object.
"""
val = self.get_cdrawings(extended=True)
paths = self.Drawpathlist()
for path in val:
npath = self.Drawpath(**path)
if npath.type != "clip":
npath.rect = Rect(path["rect"])
else:
npath.scissor = Rect(path["scissor"])
if npath.type != "group":
items = path["items"]
newitems = []
for item in items:
cmd = item[0]
rest = item[1:]
if cmd == "re":
item = ("re", Rect(rest[0]).normalize(), rest[1])
elif cmd == "qu":
item = ("qu", Quad(rest[0]))
else:
item = tuple([cmd] + [Point(i) for i in rest])
newitems.append(item)
npath.items = newitems
if npath.type == "f":
npath.stroke_opacity = None
npath.dashes = None
npath.line_join = None
npath.line_cap = None
npath.color = None
npath.width = None
paths.append(npath)
val = None
return paths
def remove_rotation(self):
"""Set page rotation to 0 while maintaining visual appearance."""
rot = self.rotation # normalized rotation value
if rot == 0:
return Identity # nothing to do
# need to derotate the page's content
mb = self.mediabox # current mediabox
if rot == 90:
# before derotation, shift content horizontally
mat0 = Matrix(1, 0, 0, 1, mb.y1 - mb.x1 - mb.x0 - mb.y0, 0)
elif rot == 270:
# before derotation, shift content vertically
mat0 = Matrix(1, 0, 0, 1, 0, mb.x1 - mb.y1 - mb.y0 - mb.x0)
else: # rot = 180
mat0 = Matrix(1, 0, 0, 1, -2 * mb.x0, -2 * mb.y0)
# prefix with derotation matrix
mat = mat0 * self.derotation_matrix
cmd = _format_g(tuple(mat)) + ' cm '
cmd = cmd.encode('utf8')
_ = TOOLS._insert_contents(self, cmd, False) # prepend to page contents
# swap x- and y-coordinates
if rot in (90, 270):
x0, y0, x1, y1 = mb
mb.x0 = y0
mb.y0 = x0
mb.x1 = y1
mb.y1 = x1
self.set_mediabox(mb)
self.set_rotation(0)
rot = ~mat # inverse of the derotation matrix
for annot in self.annots(): # modify rectangles of annotations
r = annot.rect * rot
# TODO: only try to set rectangle for applicable annot types
annot.set_rect(r)
for link in self.get_links(): # modify 'from' rectangles of links
r = link["from"] * rot
self.delete_link(link)
link["from"] = r
try: # invalid links remain deleted
self.insert_link(link)
except Exception:
pass
for widget in self.widgets(): # modify field rectangles
r = widget.rect * rot
widget.rect = r
widget.update()
return rot # the inverse of the generated derotation matrix
def cluster_drawings(
self, clip=None, drawings=None, x_tolerance: float = 3, y_tolerance: float = 3
) -> list:
"""Join rectangles of neighboring vector graphic items.
Args:
clip: optional rect-like to restrict the page area to consider.
drawings: (optional) output of a previous "get_drawings()".
x_tolerance: horizontal neighborhood threshold.
y_tolerance: vertical neighborhood threshold.
Notes:
Vector graphics (also called line-art or drawings) usually consist
of independent items like rectangles, lines or curves to jointly
form table grid lines or bar, line, pie charts and similar.
This method identifies rectangles wrapping these disparate items.
Returns:
A list of Rect items, each wrapping line-art items that are close
enough to be considered forming a common vector graphic.
Only "significant" rectangles will be returned, i.e. having both,
width and height larger than the tolerance values.
"""
CheckParent(self)
parea = self.rect # the default clipping area
if clip is not None:
parea = Rect(clip)
delta_x = x_tolerance # shorter local name
delta_y = y_tolerance # shorter local name
if drawings is None: # if we cannot re-use a previous output
drawings = self.get_drawings()
def are_neighbors(r1, r2):
"""Detect whether r1, r2 are "neighbors".
Items r1, r2 are called neighbors if the minimum distance between
their points is less-equal delta.
Both parameters must be (potentially invalid) rectangles.
"""
# normalize rectangles as needed
rr1_x0, rr1_x1 = (r1.x0, r1.x1) if r1.x1 > r1.x0 else (r1.x1, r1.x0)
rr1_y0, rr1_y1 = (r1.y0, r1.y1) if r1.y1 > r1.y0 else (r1.y1, r1.y0)
rr2_x0, rr2_x1 = (r2.x0, r2.x1) if r2.x1 > r2.x0 else (r2.x1, r2.x0)
rr2_y0, rr2_y1 = (r2.y0, r2.y1) if r2.y1 > r2.y0 else (r2.y1, r2.y0)
if (
0
or rr1_x1 < rr2_x0 - delta_x
or rr1_x0 > rr2_x1 + delta_x
or rr1_y1 < rr2_y0 - delta_y
or rr1_y0 > rr2_y1 + delta_y
):
# Rects do not overlap.
return False
else:
# Rects overlap.
return True
# exclude graphics not contained in the clip
paths = [
p
for p in drawings
if 1
and p["rect"].x0 >= parea.x0
and p["rect"].x1 <= parea.x1
and p["rect"].y0 >= parea.y0
and p["rect"].y1 <= parea.y1
]
# list of all vector graphic rectangles
prects = sorted([p["rect"] for p in paths], key=lambda r: (r.y1, r.x0))
new_rects = [] # the final list of the joined rectangles
# -------------------------------------------------------------------------
# The strategy is to identify and join all rects that are neighbors
# -------------------------------------------------------------------------
while prects: # the algorithm will empty this list
r = +prects[0] # copy of first rectangle
repeat = True
while repeat:
repeat = False
for i in range(len(prects) - 1, 0, -1): # from back to front
if are_neighbors(prects[i], r):
r |= prects[i].tl # include in first rect
r |= prects[i].br # include in first rect
del prects[i] # delete this rect
repeat = True
new_rects.append(r)
del prects[0]
prects = sorted(set(prects), key=lambda r: (r.y1, r.x0))
new_rects = sorted(set(new_rects), key=lambda r: (r.y1, r.x0))
return [r for r in new_rects if r.width > delta_x and r.height > delta_y]
def get_fonts(self, full=False):
"""List of fonts defined in the page object."""
CheckParent(self)
return self.parent.get_page_fonts(self.number, full=full)
def get_image_bbox(self, name, transform=0):
"""Get rectangle occupied by image 'name'.
'name' is either an item of the image list, or the referencing
name string - elem[7] of the resp. item.
Option 'transform' also returns the image transformation matrix.
"""
CheckParent(self)
doc = self.parent
if doc.is_closed or doc.is_encrypted:
raise ValueError('document closed or encrypted')
inf_rect = Rect(1, 1, -1, -1)
null_mat = Matrix()
if transform:
rc = (inf_rect, null_mat)
else:
rc = inf_rect
if type(name) in (list, tuple):
if not type(name[-1]) is int:
raise ValueError('need item of full page image list')
item = name
else:
imglist = [i for i in doc.get_page_images(self.number, True) if name == i[7]]
if len(imglist) == 1:
item = imglist[0]
elif imglist == []:
raise ValueError('bad image name')
else:
raise ValueError("found multiple images named '%s'." % name)
xref = item[-1]
if xref != 0 or transform is True:
try:
return self.get_image_rects(item, transform=transform)[0]
except Exception:
exception_info()
return inf_rect
pdf_page = self._pdf_page()
val = JM_image_reporter(pdf_page)
if not bool(val):
return rc
for v in val:
if v[0] != item[-3]:
continue
q = Quad(v[1])
bbox = q.rect
if transform == 0:
rc = bbox
break
hm = Matrix(util_hor_matrix(q.ll, q.lr))
h = abs(q.ll - q.ul)
w = abs(q.ur - q.ul)
m0 = Matrix(1 / w, 0, 0, 1 / h, 0, 0)
m = ~(hm * m0)
rc = (bbox, m)
break
val = rc
return val
def get_images(self, full=False):
"""List of images defined in the page object."""
CheckParent(self)
return self.parent.get_page_images(self.number, full=full)
def get_oc_items(self) -> list:
"""Get OCGs and OCMDs used in the page's contents.
Returns:
List of items (name, xref, type), where type is one of "ocg" / "ocmd",
and name is the property name.
"""
rc = []
for pname, xref in self._get_resource_properties():
text = self.parent.xref_object(xref, compressed=True)
if "/Type/OCG" in text:
octype = "ocg"
elif "/Type/OCMD" in text:
octype = "ocmd"
else:
continue
rc.append((pname, xref, octype))
return rc
def get_svg_image(self, matrix=None, text_as_path=1):
"""Make SVG image from page."""
CheckParent(self)
mediabox = mupdf.fz_bound_page(self.this)
ctm = JM_matrix_from_py(matrix)
tbounds = mediabox
text_option = mupdf.FZ_SVG_TEXT_AS_PATH if text_as_path == 1 else mupdf.FZ_SVG_TEXT_AS_TEXT
tbounds = mupdf.fz_transform_rect(tbounds, ctm)
res = mupdf.fz_new_buffer(1024)
out = mupdf.FzOutput(res)
dev = mupdf.fz_new_svg_device(
out,
tbounds.x1-tbounds.x0, # width
tbounds.y1-tbounds.y0, # height
text_option,
1,
)
mupdf.fz_run_page(self.this, dev, ctm, mupdf.FzCookie())
mupdf.fz_close_device(dev)
out.fz_close_output()
text = JM_EscapeStrFromBuffer(res)
return text
def get_textbox(
page: Page,
rect: rect_like,
textpage=None, #: TextPage = None,
) -> str:
tp = textpage
if tp is None:
tp = page.get_textpage()
elif getattr(tp, "parent") != page:
raise ValueError("not a textpage of this page")
rc = tp.extractTextbox(rect)
if textpage is None:
del tp
return rc
def get_textpage(self, clip: rect_like = None, flags: int = 0, matrix=None) -> "TextPage":
CheckParent(self)
if matrix is None:
matrix = Matrix(1, 1)
old_rotation = self.rotation
if old_rotation != 0:
self.set_rotation(0)
try:
textpage = self._get_textpage(clip, flags=flags, matrix=matrix)
finally:
if old_rotation != 0:
self.set_rotation(old_rotation)
textpage = TextPage(textpage)
textpage.parent = weakref.proxy(self)
return textpage
def get_texttrace(self):
CheckParent(self)
old_rotation = self.rotation
if old_rotation != 0:
self.set_rotation(0)
page = self.this
rc = []
if g_use_extra:
dev = extra.JM_new_texttrace_device(rc)
else:
dev = JM_new_texttrace_device(rc)
prect = mupdf.fz_bound_page(page)
dev.ptm = mupdf.FzMatrix(1, 0, 0, -1, 0, prect.y1)
mupdf.fz_run_page(page, dev, mupdf.FzMatrix(), mupdf.FzCookie())
mupdf.fz_close_device(dev)
if old_rotation != 0:
self.set_rotation(old_rotation)
return rc
def get_xobjects(self):
"""List of xobjects defined in the page object."""
CheckParent(self)
return self.parent.get_page_xobjects(self.number)
def insert_font(self, fontname="helv", fontfile=None, fontbuffer=None,
set_simple=False, wmode=0, encoding=0):
doc = self.parent
if doc is None:
raise ValueError("orphaned object: parent is None")
idx = 0
if fontname.startswith("/"):
fontname = fontname[1:]
inv_chars = INVALID_NAME_CHARS.intersection(fontname)
if inv_chars != set():
raise ValueError(f"bad fontname chars {inv_chars}")
font = CheckFont(self, fontname)
if font is not None: # font already in font list of page
xref = font[0] # this is the xref
if CheckFontInfo(doc, xref): # also in our document font list?
return xref # yes: we are done
# need to build the doc FontInfo entry - done via get_char_widths
doc.get_char_widths(xref)
return xref
#--------------------------------------------------------------------------
# the font is not present for this page
#--------------------------------------------------------------------------
bfname = Base14_fontdict.get(fontname.lower(), None) # BaseFont if Base-14 font
serif = 0
CJK_number = -1
CJK_list_n = ["china-t", "china-s", "japan", "korea"]
CJK_list_s = ["china-ts", "china-ss", "japan-s", "korea-s"]
try:
CJK_number = CJK_list_n.index(fontname)
serif = 0
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose > 1: exception_info()
pass
if CJK_number < 0:
try:
CJK_number = CJK_list_s.index(fontname)
serif = 1
except Exception:
# Verbose in PyMuPDF/tests.
if g_exceptions_verbose > 1: exception_info()
pass
if fontname.lower() in fitz_fontdescriptors.keys():
import pymupdf_fonts
fontbuffer = pymupdf_fonts.myfont(fontname) # make a copy
del pymupdf_fonts
# install the font for the page
if fontfile is not None:
if type(fontfile) is str:
fontfile_str = fontfile
elif hasattr(fontfile, "absolute"):
fontfile_str = str(fontfile)
elif hasattr(fontfile, "name"):
fontfile_str = fontfile.name
else:
raise ValueError("bad fontfile")
else:
fontfile_str = None
val = self._insertFont(fontname, bfname, fontfile_str, fontbuffer, set_simple, idx,
wmode, serif, encoding, CJK_number)
if not val: # did not work, error return
return val
xref = val[0] # xref of installed font
fontdict = val[1]
if CheckFontInfo(doc, xref): # check again: document already has this font
return xref # we are done
# need to create document font info
doc.get_char_widths(xref, fontdict=fontdict)
return xref
@property
def is_wrapped(self):
"""Check if /Contents is in a balanced graphics state."""
return self._count_q_balance() == (0, 0)
@property
def language(self):
"""Page language."""
pdfpage = _as_pdf_page(self.this, required=False)
if not pdfpage.m_internal:
return
lang = mupdf.pdf_dict_get_inheritable(pdfpage.obj(), PDF_NAME('Lang'))
if not lang.m_internal:
return
return mupdf.pdf_to_str_buf(lang)
def links(self, kinds=None):
""" Generator over the links of a page.
Args:
kinds: (list) link kinds to subselect from. If none,
all links are returned. E.g. kinds=[LINK_URI]
will only yield URI links.
"""
all_links = self.get_links()
for link in all_links:
if kinds is None or link["kind"] in kinds:
yield (link)
def load_annot(self, ident: typing.Union[str, int]) -> Annot:
"""Load an annot by name (/NM key) or xref.
Args:
ident: identifier, either name (str) or xref (int).
"""
CheckParent(self)
if type(ident) is str:
xref = 0
name = ident
elif type(ident) is int:
xref = ident
name = None
else:
raise ValueError("identifier must be a string or integer")
val = self._load_annot(name, xref)
if not val:
return val
val.thisown = True
val.parent = weakref.proxy(self)
self._annot_refs[id(val)] = val
return val
def load_links(self):
"""Get first Link."""
CheckParent(self)
val = mupdf.fz_load_links( self.this)
if not val.m_internal:
return
val = Link( val)
val.thisown = True
val.parent = weakref.proxy(self) # owning page object
self._annot_refs[id(val)] = val
val.xref = 0
val.id = ""
if self.parent.is_pdf:
xrefs = self.annot_xrefs()
xrefs = [x for x in xrefs if x[1] == mupdf.PDF_ANNOT_LINK]
if xrefs:
link_id = xrefs[0]
val.xref = link_id[0]
val.id = link_id[2]
else:
val.xref = 0
val.id = ""
return val
#----------------------------------------------------------------
# page load widget by xref
#----------------------------------------------------------------
def load_widget( self, xref):
"""Load a widget by its xref."""
CheckParent(self)
page = _as_pdf_page(self.this)
annot = JM_get_widget_by_xref( page, xref)
#log( '{=type(annot)}')
val = annot
if not val:
return val
val.thisown = True
val.parent = weakref.proxy(self)
self._annot_refs[id(val)] = val
widget = Widget()
TOOLS._fill_widget(val, widget)
val = widget
return val
@property
def mediabox(self):
"""The MediaBox."""
CheckParent(self)
page = self._pdf_page(required=False)
if not page.m_internal:
rect = mupdf.fz_bound_page( self.this)
else:
rect = JM_mediabox( page.obj())
return Rect(rect)
@property
def mediabox_size(self):
return Point(self.mediabox.x1, self.mediabox.y1)
#@property
#def parent( self):
# assert self._parent
# if self._parent:
# return self._parent
# return Document( self.this.document())
def read_contents(self):
"""All /Contents streams concatenated to one bytes object."""
return TOOLS._get_all_contents(self)
def refresh(self):
"""Refresh page after link/annot/widget updates."""
CheckParent(self)
doc = self.parent
page = doc.reload_page(self)
# fixme this looks wrong.
self.this = page
@property
def rotation(self):
"""Page rotation."""
CheckParent(self)
page = _as_pdf_page(self.this, required=0)
if not page.m_internal:
return 0
return JM_page_rotation(page)
@property
def rotation_matrix(self) -> Matrix:
"""Reflects page rotation."""
return Matrix(TOOLS._rotate_matrix(self))
def run(self, dw, m):
"""Run page through a device.
dw: DeviceWrapper
"""
CheckParent(self)
mupdf.fz_run_page(self.this, dw.device, JM_matrix_from_py(m), mupdf.FzCookie())
def set_artbox(self, rect):
"""Set the ArtBox."""
return self._set_pagebox("ArtBox", rect)
def set_bleedbox(self, rect):
"""Set the BleedBox."""
return self._set_pagebox("BleedBox", rect)
def set_contents(self, xref):
"""Set object at 'xref' as the page's /Contents."""
CheckParent(self)
doc = self.parent
if doc.is_closed:
raise ValueError("document closed")
if not doc.is_pdf:
raise ValueError("is no PDF")
if xref not in range(1, doc.xref_length()):
raise ValueError("bad xref")
if not doc.xref_is_stream(xref):
raise ValueError("xref is no stream")
doc.xref_set_key(self.xref, "Contents", "%i 0 R" % xref)
def set_cropbox(self, rect):
"""Set the CropBox. Will also change Page.rect."""
return self._set_pagebox("CropBox", rect)
def set_language(self, language=None):
"""Set PDF page default language."""
CheckParent(self)
pdfpage = _as_pdf_page(self.this)
if not language:
mupdf.pdf_dict_del(pdfpage.obj(), PDF_NAME('Lang'))
else:
lang = mupdf.fz_text_language_from_string(language)
assert hasattr(mupdf, 'fz_string_from_text_language2')
mupdf.pdf_dict_put_text_string(
pdfpage.obj,
PDF_NAME('Lang'),
mupdf.fz_string_from_text_language2(lang)
)
def set_mediabox(self, rect):
"""Set the MediaBox."""
CheckParent(self)
page = self._pdf_page()
mediabox = JM_rect_from_py(rect)
if (mupdf.fz_is_empty_rect(mediabox)
or mupdf.fz_is_infinite_rect(mediabox)
):
raise ValueError( MSG_BAD_RECT)
mupdf.pdf_dict_put_rect( page.obj(), PDF_NAME('MediaBox'), mediabox)
mupdf.pdf_dict_del( page.obj(), PDF_NAME('CropBox'))
mupdf.pdf_dict_del( page.obj(), PDF_NAME('ArtBox'))
mupdf.pdf_dict_del( page.obj(), PDF_NAME('BleedBox'))
mupdf.pdf_dict_del( page.obj(), PDF_NAME('TrimBox'))
def set_rotation(self, rotation):
"""Set page rotation."""
CheckParent(self)
page = _as_pdf_page(self.this)
rot = JM_norm_rotation(rotation)
mupdf.pdf_dict_put_int( page.obj(), PDF_NAME('Rotate'), rot)
def set_trimbox(self, rect):
"""Set the TrimBox."""
return self._set_pagebox("TrimBox", rect)
@property
def transformation_matrix(self):
"""Page transformation matrix."""
CheckParent(self)
ctm = mupdf.FzMatrix()
page = self._pdf_page(required=False)
if not page.m_internal:
return JM_py_from_matrix(ctm)
mediabox = mupdf.FzRect(mupdf.FzRect.Fixed_UNIT) # fixme: original code passed mediabox=NULL.
mupdf.pdf_page_transform(page, mediabox, ctm)
val = JM_py_from_matrix(ctm)
if self.rotation % 360 == 0:
val = Matrix(val)
else:
val = Matrix(1, 0, 0, -1, 0, self.cropbox.height)
return val
@property
def trimbox(self):
"""The TrimBox"""
rect = self._other_box("TrimBox")
if rect is None:
return self.cropbox
mb = self.mediabox
return Rect(rect[0], mb.y1 - rect[3], rect[2], mb.y1 - rect[1])
def widgets(self, types=None):
""" Generator over the widgets of a page.
Args:
types: (list) field types to subselect from. If none,
all fields are returned. E.g. types=[PDF_WIDGET_TYPE_TEXT]
will only yield text fields.
"""
#for a in self.annot_xrefs():
# log( '{a=}')
widget_xrefs = [a[0] for a in self.annot_xrefs() if a[1] == mupdf.PDF_ANNOT_WIDGET]
#log(f'widgets(): {widget_xrefs=}')
for xref in widget_xrefs:
widget = self.load_widget(xref)
if types is None or widget.field_type in types:
yield (widget)
def wrap_contents(self):
"""Ensure page is in a balanced graphics state."""
push, pop = self._count_q_balance() # count missing "q"/"Q" commands
if push > 0: # prepend required push commands
prepend = b"q\n" * push
TOOLS._insert_contents(self, prepend, False)
if pop > 0: # append required pop commands
append = b"\nQ" * pop + b"\n"
TOOLS._insert_contents(self, append, True)
@property
def xref(self):
"""PDF xref number of page."""
CheckParent(self)
return self.parent.page_xref(self.number)
rect = property(bound, doc="page rectangle")
class Pixmap:
def __init__(self, *args):
"""
Pixmap(colorspace, irect, alpha) - empty pixmap.
Pixmap(colorspace, src) - copy changing colorspace.
Pixmap(src, width, height,[clip]) - scaled copy, float dimensions.
Pixmap(src, alpha=1) - copy and add or drop alpha channel.
Pixmap(filename) - from an image in a file.
Pixmap(image) - from an image in memory (bytes).
Pixmap(colorspace, width, height, samples, alpha) - from samples data.
Pixmap(PDFdoc, xref) - from an image at xref in a PDF document.
"""
if 0:
pass
elif args_match(args,
(Colorspace, mupdf.FzColorspace),
(mupdf.FzRect, mupdf.FzIrect, IRect, Rect, tuple)
):
# create empty pixmap with colorspace and IRect
cs, rect = args
alpha = 0
pm = mupdf.fz_new_pixmap_with_bbox(cs, JM_irect_from_py(rect), mupdf.FzSeparations(0), alpha)
self.this = pm
elif args_match(args,
(Colorspace, mupdf.FzColorspace),
(mupdf.FzRect, mupdf.FzIrect, IRect, Rect, tuple),
(int, bool)
):
# create empty pixmap with colorspace and IRect
cs, rect, alpha = args
pm = mupdf.fz_new_pixmap_with_bbox(cs, JM_irect_from_py(rect), mupdf.FzSeparations(0), alpha)
self.this = pm
elif args_match(args, (Colorspace, mupdf.FzColorspace, type(None)), (Pixmap, mupdf.FzPixmap)):
# copy pixmap, converting colorspace
cs, spix = args
if isinstance(cs, Colorspace):
cs = cs.this
elif cs is None:
cs = mupdf.FzColorspace(None)
if isinstance(spix, Pixmap):
spix = spix.this
if not mupdf.fz_pixmap_colorspace(spix).m_internal:
raise ValueError( "source colorspace must not be None")
if cs.m_internal:
self.this = mupdf.fz_convert_pixmap(
spix,
cs,
mupdf.FzColorspace(),
mupdf.FzDefaultColorspaces(None),
mupdf.FzColorParams(),
1
)
else:
self.this = mupdf.fz_new_pixmap_from_alpha_channel( spix)
if not self.this.m_internal:
raise RuntimeError( MSG_PIX_NOALPHA)
elif args_match(args, (Pixmap, mupdf.FzPixmap), (Pixmap, mupdf.FzPixmap)):
# add mask to a pixmap w/o alpha channel
spix, mpix = args
if isinstance(spix, Pixmap):
spix = spix.this
if isinstance(mpix, Pixmap):
mpix = mpix.this
spm = spix
mpm = mpix
if not spix.m_internal: # intercept NULL for spix: make alpha only pix
dst = mupdf.fz_new_pixmap_from_alpha_channel(mpm)
if not dst.m_internal:
raise RuntimeError( MSG_PIX_NOALPHA)
else:
dst = mupdf.fz_new_pixmap_from_color_and_mask(spm, mpm)
self.this = dst
elif (args_match(args, (Pixmap, mupdf.FzPixmap), (float, int), (float, int), None) or
args_match(args, (Pixmap, mupdf.FzPixmap), (float, int), (float, int))):
# create pixmap as scaled copy of another one
if mupdf_version_tuple < (1, 23, 8):
assert 0, f'Cannot handle {args=} because fz_scale_pixmap() and fz_scale_pixmap_cached() are not declared in MuPDF headers'
if len(args) == 3:
spix, w, h = args
bbox = mupdf.FzIrect(mupdf.fz_infinite_irect)
else:
spix, w, h, clip = args
bbox = JM_irect_from_py(clip)
spix, w, h, clip = args
src_pix = spix.this if isinstance(spix, Pixmap) else spix
bbox = JM_irect_from_py(clip)
if not mupdf.fz_is_infinite_irect(bbox):
pm = mupdf.fz_scale_pixmap(src_pix, src_pix.x(), src_pix.y(), w, h, bbox)
else:
pm = mupdf.fz_scale_pixmap(src_pix, src_pix.x(), src_pix.y(), w, h, mupdf.FzIrect(mupdf.fz_infinite_irect))
self.this = pm
elif args_match(args, str, (Pixmap, mupdf.FzPixmap)) and args[0] == 'raw':
# Special raw construction where we set .this directly.
_, pm = args
if isinstance(pm, Pixmap):
pm = pm.this
self.this = pm
elif args_match(args, (Pixmap, mupdf.FzPixmap), (int, None)):
# Pixmap(struct Pixmap *spix, int alpha=1)
# copy pixmap & add / drop the alpha channel
spix = args[0]
alpha = args[1] if len(args) == 2 else 1
src_pix = spix.this if isinstance(spix, Pixmap) else spix
if not _INRANGE(alpha, 0, 1):
raise ValueError( "bad alpha value")
cs = mupdf.fz_pixmap_colorspace(src_pix)
if not cs.m_internal and not alpha:
raise ValueError( "cannot drop alpha for 'NULL' colorspace")
seps = mupdf.FzSeparations()
n = mupdf.fz_pixmap_colorants(src_pix)
w = mupdf.fz_pixmap_width(src_pix)
h = mupdf.fz_pixmap_height(src_pix)
pm = mupdf.fz_new_pixmap(cs, w, h, seps, alpha)
pm.m_internal.x = src_pix.m_internal.x
pm.m_internal.y = src_pix.m_internal.y
pm.m_internal.xres = src_pix.m_internal.xres
pm.m_internal.yres = src_pix.m_internal.yres
# copy samples data ------------------------------------------
if 1:
# We use specially-provided (by MuPDF Python bindings)
# ll_fz_pixmap_copy() to get best performance.
# test_pixmap.py:test_setalpha(): 3.9s t=0.0062
mupdf.ll_fz_pixmap_copy( pm.m_internal, src_pix.m_internal, n)
elif 1:
# Use memoryview.
# test_pixmap.py:test_setalpha(): 4.6 t=0.51
src_view = mupdf.fz_pixmap_samples_memoryview( src_pix)
pm_view = mupdf.fz_pixmap_samples_memoryview( pm)
if src_pix.alpha() == pm.alpha(): # identical samples
#memcpy(tptr, sptr, w * h * (n + alpha));
size = w * h * (n + alpha)
pm_view[ 0 : size] = src_view[ 0 : size]
else:
tptr = 0
sptr = 0
# This is a little faster than calling
# pm.fz_samples_set(), but still quite slow. E.g. reduces
# test_pixmap.py:test_setalpha() from 6.7s to 4.5s.
#
# t=0.53
pm_stride = pm.stride()
pm_n = pm.n()
pm_alpha = pm.alpha()
src_stride = src_pix.stride()
src_n = src_pix.n()
#log( '{=pm_stride pm_n src_stride src_n}')
for y in range( h):
for x in range( w):
pm_i = pm_stride * y + pm_n * x
src_i = src_stride * y + src_n * x
pm_view[ pm_i : pm_i + n] = src_view[ src_i : src_i + n]
if pm_alpha:
pm_view[ pm_i + n] = 255
else:
# Copy individual bytes from Python. Very slow.
# test_pixmap.py:test_setalpha(): 6.89 t=2.601
if src_pix.alpha() == pm.alpha(): # identical samples
#memcpy(tptr, sptr, w * h * (n + alpha));
for i in range(w * h * (n + alpha)):
mupdf.fz_samples_set(pm, i, mupdf.fz_samples_get(src_pix, i))
else:
# t=2.56
tptr = 0
sptr = 0
src_pix_alpha = src_pix.alpha()
for i in range(w * h):
#memcpy(tptr, sptr, n);
for j in range(n):
mupdf.fz_samples_set(pm, tptr + j, mupdf.fz_samples_get(src_pix, sptr + j))
tptr += n
if pm.alpha():
mupdf.fz_samples_set(pm, tptr, 255)
tptr += 1
sptr += n + src_pix_alpha
self.this = pm
elif args_match(args, (mupdf.FzColorspace, Colorspace), int, int, None, (int, bool)):
# create pixmap from samples data
cs, w, h, samples, alpha = args
if isinstance(cs, Colorspace):
cs = cs.this
assert isinstance(cs, mupdf.FzColorspace)
n = mupdf.fz_colorspace_n(cs)
stride = (n + alpha) * w
seps = mupdf.FzSeparations()
pm = mupdf.fz_new_pixmap(cs, w, h, seps, alpha)
if isinstance( samples, (bytes, bytearray)):
#log('using mupdf.python_buffer_data()')
samples2 = mupdf.python_buffer_data(samples)
size = len(samples)
else:
res = JM_BufferFromBytes(samples)
if not res.m_internal:
raise ValueError( "bad samples data")
size, c = mupdf.fz_buffer_storage(res)
samples2 = mupdf.python_buffer_data(samples) # raw swig proxy for `const unsigned char*`.
if stride * h != size:
raise ValueError( f"bad samples length {w=} {h=} {alpha=} {n=} {stride=} {size=}")
mupdf.ll_fz_pixmap_copy_raw( pm.m_internal, samples2)
self.this = pm
elif args_match(args, None):
# create pixmap from filename, file object, pathlib.Path or memory
imagedata, = args
name = 'name'
if hasattr(imagedata, "resolve"):
fname = imagedata.__str__()
if fname:
img = mupdf.fz_new_image_from_file(fname)
elif hasattr(imagedata, name):
fname = imagedata.name
if fname:
img = mupdf.fz_new_image_from_file(fname)
elif isinstance(imagedata, str):
img = mupdf.fz_new_image_from_file(imagedata)
else:
res = JM_BufferFromBytes(imagedata)
if not res.m_internal or not res.m_internal.len:
raise ValueError( "bad image data")
img = mupdf.fz_new_image_from_buffer(res)
# Original code passed null for subarea and ctm, but that's not
# possible with MuPDF's python bindings. The equivalent is an
# infinite rect and identify matrix scaled by img.w() and img.h().
pm, w, h = mupdf.fz_get_pixmap_from_image(
img,
mupdf.FzIrect(FZ_MIN_INF_RECT, FZ_MIN_INF_RECT, FZ_MAX_INF_RECT, FZ_MAX_INF_RECT),
mupdf.FzMatrix( img.w(), 0, 0, img.h(), 0, 0),
)
xres, yres = mupdf.fz_image_resolution(img)
pm.m_internal.xres = xres
pm.m_internal.yres = yres
self.this = pm
elif args_match(args, (Document, mupdf.FzDocument), int):
# Create pixmap from PDF image identified by XREF number
doc, xref = args
pdf = _as_pdf_document(doc)
xreflen = mupdf.pdf_xref_len(pdf)
if not _INRANGE(xref, 1, xreflen-1):
raise ValueError( MSG_BAD_XREF)
ref = mupdf.pdf_new_indirect(pdf, xref, 0)
type_ = mupdf.pdf_dict_get(ref, PDF_NAME('Subtype'))
if (not mupdf.pdf_name_eq(type_, PDF_NAME('Image'))
and not mupdf.pdf_name_eq(type_, PDF_NAME('Alpha'))
and not mupdf.pdf_name_eq(type_, PDF_NAME('Luminosity'))
):
raise ValueError( MSG_IS_NO_IMAGE)
img = mupdf.pdf_load_image(pdf, ref)
# Original code passed null for subarea and ctm, but that's not
# possible with MuPDF's python bindings. The equivalent is an
# infinite rect and identify matrix scaled by img.w() and img.h().
pix, w, h = mupdf.fz_get_pixmap_from_image(
img,
mupdf.FzIrect(FZ_MIN_INF_RECT, FZ_MIN_INF_RECT, FZ_MAX_INF_RECT, FZ_MAX_INF_RECT),
mupdf.FzMatrix(img.w(), 0, 0, img.h(), 0, 0),
)
self.this = pix
else:
text = 'Unrecognised args for constructing Pixmap:\n'
for arg in args:
text += f' {type(arg)}: {arg}\n'
raise Exception( text)
# 2024-01-16: Experimental support for a memory-view of the underlying
# data. Doesn't seem to make much difference to Pixmap.set_pixel() so
# not currently used.
self._memory_view = None
def __len__(self):
return self.size
def __repr__(self):
if not type(self) is Pixmap: return
if self.colorspace:
return "Pixmap(%s, %s, %s)" % (self.colorspace.this.m_internal.name, self.irect, self.alpha)
else:
return "Pixmap(%s, %s, %s)" % ('None', self.irect, self.alpha)
def _tobytes(self, format_, jpg_quality):
'''
Pixmap._tobytes
'''
pm = self.this
size = mupdf.fz_pixmap_stride(pm) * pm.h()
res = mupdf.fz_new_buffer(size)
out = mupdf.FzOutput(res)
if format_ == 1: mupdf.fz_write_pixmap_as_png(out, pm)
elif format_ == 2: mupdf.fz_write_pixmap_as_pnm(out, pm)
elif format_ == 3: mupdf.fz_write_pixmap_as_pam(out, pm)
elif format_ == 5: mupdf.fz_write_pixmap_as_psd(out, pm)
elif format_ == 6: mupdf.fz_write_pixmap_as_ps(out, pm)
elif format_ == 7:
if mupdf_version_tuple < (1, 24):
mupdf.fz_write_pixmap_as_jpeg(out, pm, jpg_quality)
else:
mupdf.fz_write_pixmap_as_jpeg(out, pm, jpg_quality, 0)
else:
mupdf.fz_write_pixmap_as_png(out, pm)
out.fz_close_output()
barray = JM_BinFromBuffer(res)
return barray
def _writeIMG(self, filename, format_, jpg_quality):
pm = self.this
if format_ == 1: mupdf.fz_save_pixmap_as_png(pm, filename)
elif format_ == 2: mupdf.fz_save_pixmap_as_pnm(pm, filename)
elif format_ == 3: mupdf.fz_save_pixmap_as_pam(pm, filename)
elif format_ == 5: mupdf.fz_save_pixmap_as_psd(pm, filename)
elif format_ == 6: mupdf.fz_save_pixmap_as_ps(pm, filename)
elif format_ == 7: mupdf.fz_save_pixmap_as_jpeg(pm, filename, jpg_quality)
else: mupdf.fz_save_pixmap_as_png(pm, filename)
@property
def alpha(self):
"""Indicates presence of alpha channel."""
return mupdf.fz_pixmap_alpha(self.this)
def clear_with(self, value=None, bbox=None):
"""Fill all color components with same value."""
if value is None:
mupdf.fz_clear_pixmap(self.this)
elif bbox is None:
mupdf.fz_clear_pixmap_with_value(self.this, value)
else:
JM_clear_pixmap_rect_with_value(self.this, value, JM_irect_from_py(bbox))
def color_count(self, colors=0, clip=None):
'''
Return count of each color.
'''
pm = self.this
rc = JM_color_count( pm, clip)
if not colors:
return len( rc)
return rc
def color_topusage(self, clip=None):
"""Return most frequent color and its usage ratio."""
allpixels = 0
cnt = 0
if clip is not None and self.irect in Rect(clip):
clip = self.irect
for pixel, count in self.color_count(colors=True,clip=clip).items():
allpixels += count
if count > cnt:
cnt = count
maxpixel = pixel
if not allpixels:
return (1, bytes([255] * self.n))
return (cnt / allpixels, maxpixel)
@property
def colorspace(self):
"""Pixmap Colorspace."""
return Colorspace(mupdf.fz_pixmap_colorspace(self.this))
def copy(self, src, bbox):
"""Copy bbox from another Pixmap."""
pm = self.this
src_pix = src.this
if not mupdf.fz_pixmap_colorspace(src_pix):
raise ValueError( "cannot copy pixmap with NULL colorspace")
if pm.alpha() != src_pix.alpha():
raise ValueError( "source and target alpha must be equal")
mupdf.fz_copy_pixmap_rect(pm, src_pix, JM_irect_from_py(bbox), mupdf.FzDefaultColorspaces(None))
@property
def digest(self):
"""MD5 digest of pixmap (bytes)."""
ret = mupdf.fz_md5_pixmap2(self.this)
return bytes(ret)
def gamma_with(self, gamma):
"""Apply correction with some float.
gamma=1 is a no-op."""
if not mupdf.fz_pixmap_colorspace( self.this):
message_warning("colorspace invalid for function")
return
mupdf.fz_gamma_pixmap( self.this, gamma)
@property
def h(self):
"""The height."""
return mupdf.fz_pixmap_height(self.this)
def invert_irect(self, bbox=None):
"""Invert the colors inside a bbox."""
pm = self.this
if not mupdf.fz_pixmap_colorspace(pm).m_internal:
message_warning("ignored for stencil pixmap")
return False
r = JM_irect_from_py(bbox)
if mupdf.fz_is_infinite_irect(r):
r = mupdf.fz_pixmap_bbox( pm)
return bool(JM_invert_pixmap_rect( pm, r))
@property
def irect(self):
"""Pixmap bbox - an IRect object."""
val = mupdf.fz_pixmap_bbox(self.this)
return JM_py_from_irect( val)
@property
def is_monochrome(self):
"""Check if pixmap is monochrome."""
return mupdf.fz_is_pixmap_monochrome( self.this)
@property
def is_unicolor(self):
'''
Check if pixmap has only one color.
'''
pm = self.this
n = pm.n()
count = pm.w() * pm.h() * n
def _pixmap_read_samples(pm, offset, n):
ret = list()
for i in range(n):
ret.append(mupdf.fz_samples_get(pm, offset+i))
return ret
sample0 = _pixmap_read_samples( pm, 0, n)
for offset in range( n, count, n):
sample = _pixmap_read_samples( pm, offset, n)
if sample != sample0:
return False
return True
@property
def n(self):
"""The size of one pixel."""
if g_use_extra:
# Setting self.__class__.n gives a small reduction in overhead of
# test_general.py:test_2093, e.g. 1.4x -> 1.3x.
#return extra.pixmap_n(self.this)
def n2(self):
return extra.pixmap_n(self.this)
self.__class__.n = property(n2)
return self.n
return mupdf.fz_pixmap_components(self.this)
def pdfocr_save(self, filename, compress=1, language=None, tessdata=None):
'''
Save pixmap as an OCR-ed PDF page.
'''
if not TESSDATA_PREFIX and not tessdata:
raise RuntimeError('No OCR support: TESSDATA_PREFIX not set')
opts = mupdf.FzPdfocrOptions()
opts.compress = compress
if language:
opts.language_set2( language)
if tessdata:
opts.datadir_set2( tessdata)
pix = self.this
if isinstance(filename, str):
mupdf.fz_save_pixmap_as_pdfocr( pix, filename, 0, opts)
else:
out = JM_new_output_fileptr( filename)
mupdf.fz_write_pixmap_as_pdfocr( out, pix, opts)
out.fz_close_output()
def pdfocr_tobytes(self, compress=True, language="eng", tessdata=None):
"""Save pixmap as an OCR-ed PDF page.
Args:
compress: (bool) compress, default 1 (True).
language: (str) language(s) occurring on page, default "eng" (English),
multiples like "eng+ger" for English and German.
tessdata: (str) folder name of Tesseract's language support. Must be
given if environment variable TESSDATA_PREFIX is not set.
Notes:
On failure, make sure Tesseract is installed and you have set the
environment variable "TESSDATA_PREFIX" to the folder containing your
Tesseract's language support data.
"""
if not TESSDATA_PREFIX and not tessdata:
raise RuntimeError('No OCR support: TESSDATA_PREFIX not set')
from io import BytesIO
bio = BytesIO()
self.pdfocr_save(bio, compress=compress, language=language, tessdata=tessdata)
return bio.getvalue()
def pil_save(self, *args, **kwargs):
"""Write to image file using Pillow.
Args are passed to Pillow's Image.save method, see their documentation.
Use instead of save when other output formats are desired.
"""
try:
from PIL import Image
except ImportError:
message("PIL/Pillow not installed")
raise
cspace = self.colorspace
if cspace is None:
mode = "L"
elif cspace.n == 1:
mode = "L" if self.alpha == 0 else "LA"
elif cspace.n == 3:
mode = "RGB" if self.alpha == 0 else "RGBA"
else:
mode = "CMYK"
img = Image.frombytes(mode, (self.width, self.height), self.samples)
if "dpi" not in kwargs.keys():
kwargs["dpi"] = (self.xres, self.yres)
img.save(*args, **kwargs)
def pil_tobytes(self, *args, **kwargs):
"""Convert to binary image stream using pillow.
Args are passed to Pillow's Image.save method, see their documentation.
Use instead of 'tobytes' when other output formats are needed.
"""
from io import BytesIO
bytes_out = BytesIO()
self.pil_save(bytes_out, *args, **kwargs)
return bytes_out.getvalue()
def pixel(self, x, y):
"""Get color tuple of pixel (x, y).
Last item is the alpha if Pixmap.alpha is true."""
if g_use_extra:
return extra.pixmap_pixel(self.this.m_internal, x, y)
if (0
or x < 0
or x >= self.this.m_internal.w
or y < 0
or y >= self.this.m_internal.h
):
RAISEPY(MSG_PIXEL_OUTSIDE, PyExc_ValueError)
n = self.this.m_internal.n
stride = self.this.m_internal.stride
i = stride * y + n * x
ret = tuple( self.samples_mv[ i: i+n])
return ret
@property
def samples(self)->bytes:
mv = self.samples_mv
return bytes( mv)
@property
def samples_mv(self):
'''
Pixmap samples memoryview.
'''
return mupdf.fz_pixmap_samples_memoryview(self.this)
@property
def samples_ptr(self):
return mupdf.fz_pixmap_samples_int(self.this)
def save(self, filename, output=None, jpg_quality=95):
"""Output as image in format determined by filename extension.
Args:
output: (str) only use to overrule filename extension. Default is PNG.
Others are JPEG, JPG, PNM, PGM, PPM, PBM, PAM, PSD, PS.
"""
valid_formats = {
"png": 1,
"pnm": 2,
"pgm": 2,
"ppm": 2,
"pbm": 2,
"pam": 3,
"psd": 5,
"ps": 6,
"jpg": 7,
"jpeg": 7,
}
if type(filename) is str:
pass
elif hasattr(filename, "absolute"):
filename = str(filename)
elif hasattr(filename, "name"):
filename = filename.name
if output is None:
_, ext = os.path.splitext(filename)
output = ext[1:]
idx = valid_formats.get(output.lower(), None)
if idx is None:
raise ValueError(f"Image format {output} not in {tuple(valid_formats.keys())}")
if self.alpha and idx in (2, 6, 7):
raise ValueError("'%s' cannot have alpha" % output)
if self.colorspace and self.colorspace.n > 3 and idx in (1, 2, 4):
raise ValueError(f"unsupported colorspace for '{output}'")
if idx == 7:
self.set_dpi(self.xres, self.yres)
return self._writeIMG(filename, idx, jpg_quality)
def set_alpha(self, alphavalues=None, premultiply=1, opaque=None, matte=None):
"""Set alpha channel to values contained in a byte array.
If omitted, set alphas to 255.
Args:
alphavalues: (bytes) with length (width * height) or 'None'.
premultiply: (bool, True) premultiply colors with alpha values.
opaque: (tuple, length colorspace.n) this color receives opacity 0.
matte: (tuple, length colorspace.n)) preblending background color.
"""
pix = self.this
alpha = 0
m = 0
if pix.alpha() == 0:
raise ValueError( MSG_PIX_NOALPHA)
n = mupdf.fz_pixmap_colorants(pix)
w = mupdf.fz_pixmap_width(pix)
h = mupdf.fz_pixmap_height(pix)
balen = w * h * (n+1)
colors = [0, 0, 0, 0] # make this color opaque
bgcolor = [0, 0, 0, 0] # preblending background color
zero_out = 0
bground = 0
if opaque and isinstance(opaque, (list, tuple)) and len(opaque) == n:
for i in range(n):
colors[i] = opaque[i]
zero_out = 1
if matte and isinstance( matte, (tuple, list)) and len(matte) == n:
for i in range(n):
bgcolor[i] = matte[i]
bground = 1
data = bytes()
data_len = 0
if alphavalues:
#res = JM_BufferFromBytes(alphavalues)
#data_len, data = mupdf.fz_buffer_storage(res)
#if data_len < w * h:
# THROWMSG("bad alpha values")
# fixme: don't seem to need to create an fz_buffer - can
# use <alphavalues> directly?
if isinstance(alphavalues, (bytes, bytearray)):
data = alphavalues
data_len = len(alphavalues)
else:
assert 0, f'unexpected type for alphavalues: {type(alphavalues)}'
if data_len < w * h:
raise ValueError( "bad alpha values")
if 1:
# Use C implementation for speed.
mupdf.Pixmap_set_alpha_helper(
balen,
n,
data_len,
zero_out,
mupdf.python_buffer_data( data),
pix.m_internal,
premultiply,
bground,
colors,
bgcolor,
)
else:
i = k = j = 0
data_fix = 255
while i < balen:
alpha = data[k]
if zero_out:
for j in range(i, i+n):
if mupdf.fz_samples_get(pix, j) != colors[j - i]:
data_fix = 255
break
else:
data_fix = 0
if data_len:
def fz_mul255( a, b):
x = a * b + 128
x += x // 256
return x // 256
if data_fix == 0:
mupdf.fz_samples_set(pix, i+n, 0)
else:
mupdf.fz_samples_set(pix, i+n, alpha)
if premultiply and not bground:
for j in range(i, i+n):
mupdf.fz_samples_set(pix, j, fz_mul255( mupdf.fz_samples_get(pix, j), alpha))
elif bground:
for j in range( i, i+n):
m = bgcolor[j - i]
mupdf.fz_samples_set(pix, j, fz_mul255( mupdf.fz_samples_get(pix, j) - m, alpha))
else:
mupdf.fz_samples_set(pix, i+n, data_fix)
i += n+1
k += 1
def tobytes(self, output="png", jpg_quality=95):
'''
Convert to binary image stream of desired type.
'''
valid_formats = {
"png": 1,
"pnm": 2,
"pgm": 2,
"ppm": 2,
"pbm": 2,
"pam": 3,
"tga": 4,
"tpic": 4,
"psd": 5,
"ps": 6,
'jpg': 7,
'jpeg': 7,
}
idx = valid_formats.get(output.lower(), None)
if idx is None:
raise ValueError(f"Image format {output} not in {tuple(valid_formats.keys())}")
if self.alpha and idx in (2, 6, 7):
raise ValueError("'{output}' cannot have alpha")
if self.colorspace and self.colorspace.n > 3 and idx in (1, 2, 4):
raise ValueError(f"unsupported colorspace for '{output}'")
if idx == 7:
self.set_dpi(self.xres, self.yres)
barray = self._tobytes(idx, jpg_quality)
return barray
def set_dpi(self, xres, yres):
"""Set resolution in both dimensions."""
pm = self.this
pm.m_internal.xres = xres
pm.m_internal.yres = yres
def set_origin(self, x, y):
"""Set top-left coordinates."""
pm = self.this
pm.m_internal.x = x
pm.m_internal.y = y
def set_pixel(self, x, y, color):
"""Set color of pixel (x, y)."""
if g_use_extra:
return extra.set_pixel(self.this.m_internal, x, y, color)
pm = self.this
if not _INRANGE(x, 0, pm.w() - 1) or not _INRANGE(y, 0, pm.h() - 1):
raise ValueError( MSG_PIXEL_OUTSIDE)
n = pm.n()
for j in range(n):
i = color[j]
if not _INRANGE(i, 0, 255):
raise ValueError( MSG_BAD_COLOR_SEQ)
stride = mupdf.fz_pixmap_stride( pm)
i = stride * y + n * x
if 0:
# Using a cached self._memory_view doesn't actually make much
# difference to speed.
if not self._memory_view:
self._memory_view = self.samples_mv
for j in range(n):
self._memory_view[i + j] = color[j]
else:
for j in range(n):
pm.fz_samples_set(i + j, color[j])
def set_rect(self, bbox, color):
"""Set color of all pixels in bbox."""
pm = self.this
n = pm.n()
c = []
for j in range(n):
i = color[j]
if not _INRANGE(i, 0, 255):
raise ValueError( MSG_BAD_COLOR_SEQ)
c.append(i)
bbox = JM_irect_from_py(bbox)
i = JM_fill_pixmap_rect_with_color(pm, c, bbox)
rc = bool(i)
return rc
def shrink(self, factor):
"""Divide width and height by 2**factor.
E.g. factor=1 shrinks to 25% of original size (in place)."""
if factor < 1:
message_warning("ignoring shrink factor < 1")
return
mupdf.fz_subsample_pixmap( self.this, factor)
# Pixmap has changed so clear our memory view.
self._memory_view = None
@property
def size(self):
"""Pixmap size."""
if mupdf_version_tuple >= (1, 23, 8):
return mupdf.fz_pixmap_size( self.this)
# fz_pixmap_size() is not publicly visible, so we implement it
# ourselves. fixme: we don't add on sizeof(fz_pixmap).
pm = self.this
return pm.n() * pm.w() * pm.h()
@property
def stride(self):
"""Length of one image line (width * n)."""
return self.this.stride()
def tint_with(self, black, white):
"""Tint colors with modifiers for black and white."""
if not self.colorspace or self.colorspace.n > 3:
message("warning: colorspace invalid for function")
return
return mupdf.fz_tint_pixmap( self.this, black, white)
@property
def w(self):
"""The width."""
return mupdf.fz_pixmap_width(self.this)
def warp(self, quad, width, height):
"""Return pixmap from a warped quad."""
if not quad.is_convex: raise ValueError("quad must be convex")
q = JM_quad_from_py(quad)
points = [ q.ul, q.ur, q.lr, q.ll]
dst = mupdf.fz_warp_pixmap( self.this, points, width, height)
return Pixmap( dst)
@property
def x(self):
"""x component of Pixmap origin."""
return mupdf.fz_pixmap_x(self.this)
@property
def xres(self):
"""Resolution in x direction."""
return self.this.xres()
@property
def y(self):
"""y component of Pixmap origin."""
return mupdf.fz_pixmap_y(self.this)
@property
def yres(self):
"""Resolution in y direction."""
return self.this.yres()
width = w
height = h
del Point
class Point:
def __abs__(self):
return math.sqrt(self.x * self.x + self.y * self.y)
def __add__(self, p):
if hasattr(p, "__float__"):
return Point(self.x + p, self.y + p)
if len(p) != 2:
raise ValueError("Point: bad seq len")
return Point(self.x + p[0], self.y + p[1])
def __bool__(self):
return not (max(self) == min(self) == 0)
def __eq__(self, p):
if not hasattr(p, "__len__"):
return False
return len(p) == 2 and bool(self - p) is False
def __getitem__(self, i):
return (self.x, self.y)[i]
def __hash__(self):
return hash(tuple(self))
def __init__(self, *args, x=None, y=None):
'''
Point() - all zeros
Point(x, y)
Point(Point) - new copy
Point(sequence) - from 'sequence'
Explicit keyword args x, y override earlier settings if not None.
'''
if not args:
self.x = 0.0
self.y = 0.0
elif len(args) > 2:
raise ValueError("Point: bad seq len")
elif len(args) == 2:
self.x = float(args[0])
self.y = float(args[1])
elif len(args) == 1:
l = args[0]
if isinstance(l, (mupdf.FzPoint, mupdf.fz_point)):
self.x = l.x
self.y = l.y
else:
if hasattr(l, "__getitem__") is False:
raise ValueError("Point: bad args")
if len(l) != 2:
raise ValueError("Point: bad seq len")
self.x = float(l[0])
self.y = float(l[1])
else:
raise ValueError("Point: bad seq len")
if x is not None: self.x = x
if y is not None: self.y = y
def __len__(self):
return 2
def __mul__(self, m):
if hasattr(m, "__float__"):
return Point(self.x * m, self.y * m)
p = Point(self)
return p.transform(m)
def __neg__(self):
return Point(-self.x, -self.y)
def __nonzero__(self):
return not (max(self) == min(self) == 0)
def __pos__(self):
return Point(self)
def __repr__(self):
return "Point" + str(tuple(self))
def __setitem__(self, i, v):
v = float(v)
if i == 0: self.x = v
elif i == 1: self.y = v
else:
raise IndexError("index out of range")
return None
def __sub__(self, p):
if hasattr(p, "__float__"):
return Point(self.x - p, self.y - p)
if len(p) != 2:
raise ValueError("Point: bad seq len")
return Point(self.x - p[0], self.y - p[1])
def __truediv__(self, m):
if hasattr(m, "__float__"):
return Point(self.x * 1./m, self.y * 1./m)
m1 = util_invert_matrix(m)[1]
if not m1:
raise ZeroDivisionError("matrix not invertible")
p = Point(self)
return p.transform(m1)
@property
def abs_unit(self):
"""Unit vector with positive coordinates."""
s = self.x * self.x + self.y * self.y
if s < EPSILON:
return Point(0,0)
s = math.sqrt(s)
return Point(abs(self.x) / s, abs(self.y) / s)
def distance_to(self, *args):
"""Return distance to rectangle or another point."""
if not len(args) > 0:
raise ValueError("at least one parameter must be given")
x = args[0]
if len(x) == 2:
x = Point(x)
elif len(x) == 4:
x = Rect(x)
else:
raise ValueError("arg1 must be point-like or rect-like")
if len(args) > 1:
unit = args[1]
else:
unit = "px"
u = {"px": (1.,1.), "in": (1.,72.), "cm": (2.54, 72.),
"mm": (25.4, 72.)}
f = u[unit][0] / u[unit][1]
if type(x) is Point:
return abs(self - x) * f
# from here on, x is a rectangle
# as a safeguard, make a finite copy of it
r = Rect(x.top_left, x.top_left)
r = r | x.bottom_right
if self in r:
return 0.0
if self.x > r.x1:
if self.y >= r.y1:
return self.distance_to(r.bottom_right, unit)
elif self.y <= r.y0:
return self.distance_to(r.top_right, unit)
else:
return (self.x - r.x1) * f
elif r.x0 <= self.x <= r.x1:
if self.y >= r.y1:
return (self.y - r.y1) * f
else:
return (r.y0 - self.y) * f
else:
if self.y >= r.y1:
return self.distance_to(r.bottom_left, unit)
elif self.y <= r.y0:
return self.distance_to(r.top_left, unit)
else:
return (r.x0 - self.x) * f
def transform(self, m):
"""Replace point by its transformation with matrix-like m."""
if len(m) != 6:
raise ValueError("Matrix: bad seq len")
self.x, self.y = util_transform_point(self, m)
return self
@property
def unit(self):
"""Unit vector of the point."""
s = self.x * self.x + self.y * self.y
if s < EPSILON:
return Point(0,0)
s = math.sqrt(s)
return Point(self.x / s, self.y / s)
__div__ = __truediv__
norm = __abs__
class Quad:
def __abs__(self):
if self.is_empty:
return 0.0
return abs(self.ul - self.ur) * abs(self.ul - self.ll)
def __add__(self, q):
if hasattr(q, "__float__"):
return Quad(self.ul + q, self.ur + q, self.ll + q, self.lr + q)
if len(q) != 4:
raise ValueError("Quad: bad seq len")
return Quad(self.ul + q[0], self.ur + q[1], self.ll + q[2], self.lr + q[3])
def __bool__(self):
return not self.is_empty
def __contains__(self, x):
try:
l = x.__len__()
except Exception:
if g_exceptions_verbose > 1: exception_info()
return False
if l == 2:
return util_point_in_quad(x, self)
if l != 4:
return False
if CheckRect(x):
if Rect(x).is_empty:
return True
return util_point_in_quad(x[:2], self) and util_point_in_quad(x[2:], self)
if CheckQuad(x):
for i in range(4):
if not util_point_in_quad(x[i], self):
return False
return True
return False
def __eq__(self, quad):
if not hasattr(quad, "__len__"):
return False
return len(quad) == 4 and (
self.ul == quad[0] and
self.ur == quad[1] and
self.ll == quad[2] and
self.lr == quad[3]
)
def __getitem__(self, i):
return (self.ul, self.ur, self.ll, self.lr)[i]
def __hash__(self):
return hash(tuple(self))
def __init__(self, *args, ul=None, ur=None, ll=None, lr=None):
'''
Quad() - all zero points
Quad(ul, ur, ll, lr)
Quad(quad) - new copy
Quad(sequence) - from 'sequence'
Explicit keyword args ul, ur, ll, lr override earlier settings if not
None.
'''
if not args:
self.ul = self.ur = self.ll = self.lr = Point()
elif len(args) > 4:
raise ValueError("Quad: bad seq len")
elif len(args) == 4:
self.ul, self.ur, self.ll, self.lr = map(Point, args)
elif len(args) == 1:
l = args[0]
if isinstance(l, mupdf.FzQuad):
self.this = l
self.ul, self.ur, self.ll, self.lr = Point(l.ul), Point(l.ur), Point(l.ll), Point(l.lr)
elif hasattr(l, "__getitem__") is False:
raise ValueError("Quad: bad args")
elif len(l) != 4:
raise ValueError("Quad: bad seq len")
else:
self.ul, self.ur, self.ll, self.lr = map(Point, l)
else:
raise ValueError("Quad: bad args")
if ul is not None: self.ul = Point(ul)
if ur is not None: self.ur = Point(ur)
if ll is not None: self.ll = Point(ll)
if lr is not None: self.lr = Point(lr)
def __len__(self):
return 4
def __mul__(self, m):
q = Quad(self)
q = q.transform(m)
return q
def __neg__(self):
return Quad(-self.ul, -self.ur, -self.ll, -self.lr)
def __nonzero__(self):
return not self.is_empty
def __pos__(self):
return Quad(self)
def __repr__(self):
return "Quad" + str(tuple(self))
def __setitem__(self, i, v):
if i == 0: self.ul = Point(v)
elif i == 1: self.ur = Point(v)
elif i == 2: self.ll = Point(v)
elif i == 3: self.lr = Point(v)
else:
raise IndexError("index out of range")
return None
def __sub__(self, q):
if hasattr(q, "__float__"):
return Quad(self.ul - q, self.ur - q, self.ll - q, self.lr - q)
if len(q) != 4:
raise ValueError("Quad: bad seq len")
return Quad(self.ul - q[0], self.ur - q[1], self.ll - q[2], self.lr - q[3])
def __truediv__(self, m):
if hasattr(m, "__float__"):
im = 1. / m
else:
im = util_invert_matrix(m)[1]
if not im:
raise ZeroDivisionError("Matrix not invertible")
q = Quad(self)
q = q.transform(im)
return q
@property
def is_convex(self):
"""Check if quad is convex and not degenerate.
Notes:
Check that for the two diagonals, the other two corners are not
on the same side of the diagonal.
Returns:
True or False.
"""
m = planish_line(self.ul, self.lr) # puts this diagonal on x-axis
p1 = self.ll * m # transform the
p2 = self.ur * m # other two points
if p1.y * p2.y > 0:
return False
m = planish_line(self.ll, self.ur) # puts other diagonal on x-axis
p1 = self.lr * m # transform the
p2 = self.ul * m # remaining points
if p1.y * p2.y > 0:
return False
return True
@property
def is_empty(self):
"""Check whether all quad corners are on the same line.
This is the case if width or height is zero.
"""
return self.width < EPSILON or self.height < EPSILON
@property
def is_infinite(self):
"""Check whether this is the infinite quad."""
return self.rect.is_infinite
@property
def is_rectangular(self):
"""Check if quad is rectangular.
Notes:
Some rotation matrix can thus transform it into a rectangle.
This is equivalent to three corners enclose 90 degrees.
Returns:
True or False.
"""
sine = util_sine_between(self.ul, self.ur, self.lr)
if abs(sine - 1) > EPSILON: # the sine of the angle
return False
sine = util_sine_between(self.ur, self.lr, self.ll)
if abs(sine - 1) > EPSILON:
return False
sine = util_sine_between(self.lr, self.ll, self.ul)
if abs(sine - 1) > EPSILON:
return False
return True
def morph(self, p, m):
"""Morph the quad with matrix-like 'm' and point-like 'p'.
Return a new quad."""
if self.is_infinite:
return INFINITE_QUAD()
delta = Matrix(1, 1).pretranslate(p.x, p.y)
q = self * ~delta * m * delta
return q
@property
def rect(self):
r = Rect()
r.x0 = min(self.ul.x, self.ur.x, self.lr.x, self.ll.x)
r.y0 = min(self.ul.y, self.ur.y, self.lr.y, self.ll.y)
r.x1 = max(self.ul.x, self.ur.x, self.lr.x, self.ll.x)
r.y1 = max(self.ul.y, self.ur.y, self.lr.y, self.ll.y)
return r
def transform(self, m):
"""Replace quad by its transformation with matrix m."""
if hasattr(m, "__float__"):
pass
elif len(m) != 6:
raise ValueError("Matrix: bad seq len")
self.ul *= m
self.ur *= m
self.ll *= m
self.lr *= m
return self
__div__ = __truediv__
width = property(lambda self: max(abs(self.ul - self.ur), abs(self.ll - self.lr)))
height = property(lambda self: max(abs(self.ul - self.ll), abs(self.ur - self.lr)))
class Rect:
def __abs__(self):
if self.is_empty or self.is_infinite:
return 0.0
return (self.x1 - self.x0) * (self.y1 - self.y0)
def __add__(self, p):
if hasattr(p, "__float__"):
return Rect(self.x0 + p, self.y0 + p, self.x1 + p, self.y1 + p)
if len(p) != 4:
raise ValueError("Rect: bad seq len")
return Rect(self.x0 + p[0], self.y0 + p[1], self.x1 + p[2], self.y1 + p[3])
def __and__(self, x):
if not hasattr(x, "__len__"):
raise ValueError("bad operand 2")
r1 = Rect(x)
r = Rect(self)
return r.intersect(r1)
def __bool__(self):
return not (max(self) == min(self) == 0)
def __contains__(self, x):
if hasattr(x, "__float__"):
return x in tuple(self)
l = len(x)
if l == 2:
return util_is_point_in_rect(x, self)
if l == 4:
r = INFINITE_RECT()
try:
r = Rect(x)
except Exception:
if g_exceptions_verbose > 1: exception_info()
r = Quad(x).rect
return (self.x0 <= r.x0 <= r.x1 <= self.x1 and
self.y0 <= r.y0 <= r.y1 <= self.y1)
return False
def __eq__(self, rect):
if not hasattr(rect, "__len__"):
return False
return len(rect) == 4 and bool(self - rect) is False
def __getitem__(self, i):
return (self.x0, self.y0, self.x1, self.y1)[i]
def __hash__(self):
return hash(tuple(self))
def __init__(self, *args, p0=None, p1=None, x0=None, y0=None, x1=None, y1=None):
"""
Rect() - all zeros
Rect(x0, y0, x1, y1)
Rect(top-left, x1, y1)
Rect(x0, y0, bottom-right)
Rect(top-left, bottom-right)
Rect(Rect or IRect) - new copy
Rect(sequence) - from 'sequence'
Explicit keyword args p0, p1, x0, y0, x1, y1 override earlier settings
if not None.
"""
x0, y0, x1, y1 = util_make_rect( *args, p0=p0, p1=p1, x0=x0, y0=y0, x1=x1, y1=y1)
self.x0 = float( x0)
self.y0 = float( y0)
self.x1 = float( x1)
self.y1 = float( y1)
def __len__(self):
return 4
def __mul__(self, m):
if hasattr(m, "__float__"):
return Rect(self.x0 * m, self.y0 * m, self.x1 * m, self.y1 * m)
r = Rect(self)
r = r.transform(m)
return r
def __neg__(self):
return Rect(-self.x0, -self.y0, -self.x1, -self.y1)
def __nonzero__(self):
return not (max(self) == min(self) == 0)
def __or__(self, x):
if not hasattr(x, "__len__"):
raise ValueError("bad operand 2")
r = Rect(self)
if len(x) == 2:
return r.include_point(x)
if len(x) == 4:
return r.include_rect(x)
raise ValueError("bad operand 2")
def __pos__(self):
return Rect(self)
def __repr__(self):
return "Rect" + str(tuple(self))
def __setitem__(self, i, v):
v = float(v)
if i == 0: self.x0 = v
elif i == 1: self.y0 = v
elif i == 2: self.x1 = v
elif i == 3: self.y1 = v
else:
raise IndexError("index out of range")
return None
def __sub__(self, p):
if hasattr(p, "__float__"):
return Rect(self.x0 - p, self.y0 - p, self.x1 - p, self.y1 - p)
if len(p) != 4:
raise ValueError("Rect: bad seq len")
return Rect(self.x0 - p[0], self.y0 - p[1], self.x1 - p[2], self.y1 - p[3])
def __truediv__(self, m):
if hasattr(m, "__float__"):
return Rect(self.x0 * 1./m, self.y0 * 1./m, self.x1 * 1./m, self.y1 * 1./m)
im = util_invert_matrix(m)[1]
if not im:
raise ZeroDivisionError(f"Matrix not invertible: {m}")
r = Rect(self)
r = r.transform(im)
return r
@property
def bottom_left(self):
"""Bottom-left corner."""
return Point(self.x0, self.y1)
@property
def bottom_right(self):
"""Bottom-right corner."""
return Point(self.x1, self.y1)
def contains(self, x):
"""Check if containing point-like or rect-like x."""
return self.__contains__(x)
@property
def height(self):
return max(0, self.y1 - self.y0)
def include_point(self, p):
"""Extend to include point-like p."""
if len(p) != 2:
raise ValueError("Point: bad seq len")
self.x0, self.y0, self.x1, self.y1 = util_include_point_in_rect(self, p)
return self
def include_rect(self, r):
"""Extend to include rect-like r."""
if len(r) != 4:
raise ValueError("Rect: bad seq len")
r = Rect(r)
if r.is_infinite or self.is_infinite:
self.x0, self.y0, self.x1, self.y1 = FZ_MIN_INF_RECT, FZ_MIN_INF_RECT, FZ_MAX_INF_RECT, FZ_MAX_INF_RECT
elif r.is_empty:
return self
elif self.is_empty:
self.x0, self.y0, self.x1, self.y1 = r.x0, r.y0, r.x1, r.y1
else:
self.x0, self.y0, self.x1, self.y1 = util_union_rect(self, r)
return self
def intersect(self, r):
"""Restrict to common rect with rect-like r."""
if not len(r) == 4:
raise ValueError("Rect: bad seq len")
r = Rect(r)
if r.is_infinite:
return self
elif self.is_infinite:
self.x0, self.y0, self.x1, self.y1 = r.x0, r.y0, r.x1, r.y1
elif r.is_empty:
self.x0, self.y0, self.x1, self.y1 = r.x0, r.y0, r.x1, r.y1
elif self.is_empty:
return self
else:
self.x0, self.y0, self.x1, self.y1 = util_intersect_rect(self, r)
return self
def intersects(self, x):
"""Check if intersection with rectangle x is not empty."""
r1 = Rect(x)
if self.is_empty or self.is_infinite or r1.is_empty or r1.is_infinite:
return False
r = Rect(self)
if r.intersect(r1).is_empty:
return False
return True
@property
def is_empty(self):
"""True if rectangle area is empty."""
return self.x0 >= self.x1 or self.y0 >= self.y1
@property
def is_infinite(self):
"""True if this is the infinite rectangle."""
return self.x0 == self.y0 == FZ_MIN_INF_RECT and self.x1 == self.y1 == FZ_MAX_INF_RECT
@property
def is_valid(self):
"""True if rectangle is valid."""
return self.x0 <= self.x1 and self.y0 <= self.y1
def morph(self, p, m):
"""Morph with matrix-like m and point-like p.
Returns a new quad."""
if self.is_infinite:
return INFINITE_QUAD()
return self.quad.morph(p, m)
def norm(self):
return math.sqrt(sum([c*c for c in self]))
def normalize(self):
"""Replace rectangle with its finite version."""
if self.x1 < self.x0:
self.x0, self.x1 = self.x1, self.x0
if self.y1 < self.y0:
self.y0, self.y1 = self.y1, self.y0
return self
@property
def quad(self):
"""Return Quad version of rectangle."""
return Quad(self.tl, self.tr, self.bl, self.br)
def round(self):
"""Return the IRect."""
return IRect(util_round_rect(self))
@property
def top_left(self):
"""Top-left corner."""
return Point(self.x0, self.y0)
@property
def top_right(self):
"""Top-right corner."""
return Point(self.x1, self.y0)
def torect(self, r):
"""Return matrix that converts to target rect."""
r = Rect(r)
if self.is_infinite or self.is_empty or r.is_infinite or r.is_empty:
raise ValueError("rectangles must be finite and not empty")
return (
Matrix(1, 0, 0, 1, -self.x0, -self.y0)
* Matrix(r.width / self.width, r.height / self.height)
* Matrix(1, 0, 0, 1, r.x0, r.y0)
)
def transform(self, m):
"""Replace with the transformation by matrix-like m."""
if not len(m) == 6:
raise ValueError("Matrix: bad seq len")
self.x0, self.y0, self.x1, self.y1 = util_transform_rect(self, m)
return self
@property
def width(self):
return max(0, self.x1 - self.x0)
__div__ = __truediv__
bl = bottom_left
br = bottom_right
irect = property(round)
tl = top_left
tr = top_right
class Shape:
"""Create a new shape."""
def __init__(self, page: Page):
CheckParent(page)
self.page = page
self.doc = page.parent
if not self.doc.is_pdf:
raise ValueError("not a PDF")
self.height = page.mediabox_size.y
self.width = page.mediabox_size.x
self.x = page.cropbox_position.x
self.y = page.cropbox_position.y
self.pctm = page.transformation_matrix # page transf. matrix
self.ipctm = ~self.pctm # inverted transf. matrix
self.draw_cont = ""
self.text_cont = ""
self.totalcont = ""
self.last_point = None
self.rect = None
def commit(self, overlay: bool = True) -> None:
"""
Update the page's /Contents object with Shape data. The argument
controls whether data appear in foreground (default) or background.
"""
CheckParent(self.page) # doc may have died meanwhile
self.totalcont += self.text_cont
self.totalcont = self.totalcont.encode()
if self.totalcont != b"":
# make /Contents object with dummy stream
xref = TOOLS._insert_contents(self.page, b" ", overlay)
# update it with potential compression
mupdf.pdf_update_stream(self.doc, xref, self.totalcont)
self.last_point = None # clean up ...
self.rect = None #
self.draw_cont = "" # for potential ...
self.text_cont = "" # ...
self.totalcont = "" # re-use
return
def draw_bezier(
self,
p1: point_like,
p2: point_like,
p3: point_like,
p4: point_like,
):# -> Point:
"""Draw a standard cubic Bezier curve."""
p1 = Point(p1)
p2 = Point(p2)
p3 = Point(p3)
p4 = Point(p4)
if not (self.last_point == p1):
args = JM_TUPLE(p1 * self.ipctm)
self.draw_cont += f"{_format_g(args)} m\n"
args = JM_TUPLE(list(p2 * self.ipctm) + list(p3 * self.ipctm) + list(p4 * self.ipctm))
self.draw_cont += f"{_format_g(args)} c\n"
self.updateRect(p1)
self.updateRect(p2)
self.updateRect(p3)
self.updateRect(p4)
self.last_point = p4
return self.last_point
def draw_circle(self, center: point_like, radius: float):# -> Point:
"""Draw a circle given its center and radius."""
if not radius > EPSILON:
raise ValueError("radius must be positive")
center = Point(center)
p1 = center - (radius, 0)
return self.draw_sector(center, p1, 360, fullSector=False)
def draw_curve(
self,
p1: point_like,
p2: point_like,
p3: point_like,
):# -> Point:
"""Draw a curve between points using one control point."""
kappa = 0.55228474983
p1 = Point(p1)
p2 = Point(p2)
p3 = Point(p3)
k1 = p1 + (p2 - p1) * kappa
k2 = p3 + (p2 - p3) * kappa
return self.draw_bezier(p1, k1, k2, p3)
def draw_line(self, p1: point_like, p2: point_like):# -> Point:
"""Draw a line between two points."""
p1 = Point(p1)
p2 = Point(p2)
if not (self.last_point == p1):
self.draw_cont += _format_g(JM_TUPLE(p1 * self.ipctm)) + " m\n"
self.last_point = p1
self.updateRect(p1)
self.draw_cont += _format_g(JM_TUPLE(p2 * self.ipctm)) + " l\n"
self.updateRect(p2)
self.last_point = p2
return self.last_point
def draw_oval(self, tetra: typing.Union[quad_like, rect_like]):# -> Point:
"""Draw an ellipse inside a tetrapod."""
if len(tetra) != 4:
raise ValueError("invalid arg length")
if hasattr(tetra[0], "__float__"):
q = Rect(tetra).quad
else:
q = Quad(tetra)
mt = q.ul + (q.ur - q.ul) * 0.5
mr = q.ur + (q.lr - q.ur) * 0.5
mb = q.ll + (q.lr - q.ll) * 0.5
ml = q.ul + (q.ll - q.ul) * 0.5
if not (self.last_point == ml):
self.draw_cont += _format_g(JM_TUPLE(ml * self.ipctm)) + " m\n"
self.last_point = ml
self.draw_curve(ml, q.ll, mb)
self.draw_curve(mb, q.lr, mr)
self.draw_curve(mr, q.ur, mt)
self.draw_curve(mt, q.ul, ml)
self.updateRect(q.rect)
self.last_point = ml
return self.last_point
def draw_polyline(self, points: list):# -> Point:
"""Draw several connected line segments."""
for i, p in enumerate(points):
if i == 0:
if not (self.last_point == Point(p)):
self.draw_cont += _format_g(JM_TUPLE(Point(p) * self.ipctm)) + " m\n"
self.last_point = Point(p)
else:
self.draw_cont += _format_g(JM_TUPLE(Point(p) * self.ipctm)) + " l\n"
self.updateRect(p)
self.last_point = Point(points[-1])
return self.last_point
def draw_quad(self, quad: quad_like):# -> Point:
"""Draw a Quad."""
q = Quad(quad)
return self.draw_polyline([q.ul, q.ll, q.lr, q.ur, q.ul])
def draw_rect(self, rect: rect_like):# -> Point:
"""Draw a rectangle."""
r = Rect(rect)
args = JM_TUPLE(list(r.bl * self.ipctm) + [r.width, r.height])
self.draw_cont += _format_g(args) + " re\n"
self.updateRect(r)
self.last_point = r.tl
return self.last_point
def draw_sector(
self,
center: point_like,
point: point_like,
beta: float,
fullSector: bool = True,
):# -> Point:
"""Draw a circle sector."""
center = Point(center)
point = Point(point)
def l3(a, b):
return _format_g((a, b)) + " m\n"
def l4(a, b, c, d, e, f):
return _format_g((a, b, c, d, e, f)) + " c\n"
def l5(a, b):
return _format_g((a, b)) + " l\n"
betar = math.radians(-beta)
w360 = math.radians(math.copysign(360, betar)) * (-1)
w90 = math.radians(math.copysign(90, betar))
w45 = w90 / 2
while abs(betar) > 2 * math.pi:
betar += w360 # bring angle below 360 degrees
if not (self.last_point == point):
self.draw_cont += l3(JM_TUPLE(point * self.ipctm))
self.last_point = point
Q = Point(0, 0) # just make sure it exists
C = center
P = point
S = P - C # vector 'center' -> 'point'
rad = abs(S) # circle radius
if not rad > EPSILON:
raise ValueError("radius must be positive")
alfa = self.horizontal_angle(center, point)
while abs(betar) > abs(w90): # draw 90 degree arcs
q1 = C.x + math.cos(alfa + w90) * rad
q2 = C.y + math.sin(alfa + w90) * rad
Q = Point(q1, q2) # the arc's end point
r1 = C.x + math.cos(alfa + w45) * rad / math.cos(w45)
r2 = C.y + math.sin(alfa + w45) * rad / math.cos(w45)
R = Point(r1, r2) # crossing point of tangents
kappah = (1 - math.cos(w45)) * 4 / 3 / abs(R - Q)
kappa = kappah * abs(P - Q)
cp1 = P + (R - P) * kappa # control point 1
cp2 = Q + (R - Q) * kappa # control point 2
self.draw_cont += l4(JM_TUPLE(
list(cp1 * self.ipctm) + list(cp2 * self.ipctm) + list(Q * self.ipctm)
))
betar -= w90 # reduce param angle by 90 deg
alfa += w90 # advance start angle by 90 deg
P = Q # advance to arc end point
# draw (remaining) arc
if abs(betar) > 1e-3: # significant degrees left?
beta2 = betar / 2
q1 = C.x + math.cos(alfa + betar) * rad
q2 = C.y + math.sin(alfa + betar) * rad
Q = Point(q1, q2) # the arc's end point
r1 = C.x + math.cos(alfa + beta2) * rad / math.cos(beta2)
r2 = C.y + math.sin(alfa + beta2) * rad / math.cos(beta2)
R = Point(r1, r2) # crossing point of tangents
# kappa height is 4/3 of segment height
kappah = (1 - math.cos(beta2)) * 4 / 3 / abs(R - Q) # kappa height
kappa = kappah * abs(P - Q) / (1 - math.cos(betar))
cp1 = P + (R - P) * kappa # control point 1
cp2 = Q + (R - Q) * kappa # control point 2
self.draw_cont += l4(JM_TUPLE(
list(cp1 * self.ipctm) + list(cp2 * self.ipctm) + list(Q * self.ipctm)
))
if fullSector:
self.draw_cont += l3(JM_TUPLE(point * self.ipctm))
self.draw_cont += l5(JM_TUPLE(center * self.ipctm))
self.draw_cont += l5(JM_TUPLE(Q * self.ipctm))
self.last_point = Q
return self.last_point
def draw_squiggle(
self,
p1: point_like,
p2: point_like,
breadth=2,
):# -> Point:
"""Draw a squiggly line from p1 to p2."""
p1 = Point(p1)
p2 = Point(p2)
S = p2 - p1 # vector start - end
rad = abs(S) # distance of points
cnt = 4 * int(round(rad / (4 * breadth), 0)) # always take full phases
if cnt < 4:
raise ValueError("points too close")
mb = rad / cnt # revised breadth
matrix = Matrix(TOOLS._hor_matrix(p1, p2)) # normalize line to x-axis
i_mat = ~matrix # get original position
k = 2.4142135623765633 # y of draw_curve helper point
points = [] # stores edges
for i in range(1, cnt):
if i % 4 == 1: # point "above" connection
p = Point(i, -k) * mb
elif i % 4 == 3: # point "below" connection
p = Point(i, k) * mb
else: # else on connection line
p = Point(i, 0) * mb
points.append(p * i_mat)
points = [p1] + points + [p2]
cnt = len(points)
i = 0
while i + 2 < cnt:
self.draw_curve(points[i], points[i + 1], points[i + 2])
i += 2
return p2
def draw_zigzag(
self,
p1: point_like,
p2: point_like,
breadth: float = 2,
):# -> Point:
"""Draw a zig-zagged line from p1 to p2."""
p1 = Point(p1)
p2 = Point(p2)
S = p2 - p1 # vector start - end
rad = abs(S) # distance of points
cnt = 4 * int(round(rad / (4 * breadth), 0)) # always take full phases
if cnt < 4:
raise ValueError("points too close")
mb = rad / cnt # revised breadth
matrix = Matrix(TOOLS._hor_matrix(p1, p2)) # normalize line to x-axis
i_mat = ~matrix # get original position
points = [] # stores edges
for i in range(1, cnt):
if i % 4 == 1: # point "above" connection
p = Point(i, -1) * mb
elif i % 4 == 3: # point "below" connection
p = Point(i, 1) * mb
else: # ignore others
continue
points.append(p * i_mat)
self.draw_polyline([p1] + points + [p2]) # add start and end points
return p2
def finish(
self,
width: float = 1,
color: OptSeq = (0,),
fill: OptSeq = None,
lineCap: int = 0,
lineJoin: int = 0,
dashes: OptStr = None,
even_odd: bool = False,
morph: OptSeq = None,
closePath: bool = True,
fill_opacity: float = 1,
stroke_opacity: float = 1,
oc: int = 0,
) -> None:
"""Finish the current drawing segment.
Notes:
Apply colors, opacity, dashes, line style and width, or
morphing. Also whether to close the path
by connecting last to first point.
"""
if self.draw_cont == "": # treat empty contents as no-op
return
if width == 0: # border color makes no sense then
color = None
elif color is None: # vice versa
width = 0
# if color == None and fill == None:
# raise ValueError("at least one of 'color' or 'fill' must be given")
color_str = ColorCode(color, "c") # ensure proper color string
fill_str = ColorCode(fill, "f") # ensure proper fill string
optcont = self.page._get_optional_content(oc)
if optcont is not None:
self.draw_cont = "/OC /%s BDC\n" % optcont + self.draw_cont
emc = "EMC\n"
else:
emc = ""
alpha = self.page._set_opacity(CA=stroke_opacity, ca=fill_opacity)
if alpha is not None:
self.draw_cont = "/%s gs\n" % alpha + self.draw_cont
if width != 1 and width != 0:
self.draw_cont += _format_g(width) + " w\n"
if lineCap != 0:
self.draw_cont = "%i J\n" % lineCap + self.draw_cont
if lineJoin != 0:
self.draw_cont = "%i j\n" % lineJoin + self.draw_cont
if dashes not in (None, "", "[] 0"):
self.draw_cont = "%s d\n" % dashes + self.draw_cont
if closePath:
self.draw_cont += "h\n"
self.last_point = None
if color is not None:
self.draw_cont += color_str
if fill is not None:
self.draw_cont += fill_str
if color is not None:
if not even_odd:
self.draw_cont += "B\n"
else:
self.draw_cont += "B*\n"
else:
if not even_odd:
self.draw_cont += "f\n"
else:
self.draw_cont += "f*\n"
else:
self.draw_cont += "S\n"
self.draw_cont += emc
if CheckMorph(morph):
m1 = Matrix(
1, 0, 0, 1, morph[0].x + self.x, self.height - morph[0].y - self.y
)
mat = ~m1 * morph[1] * m1
self.draw_cont = _format_g(JM_TUPLE(mat) + self.draw_cont) + " cm\n"
self.totalcont += "\nq\n" + self.draw_cont + "Q\n"
self.draw_cont = ""
self.last_point = None
return
@staticmethod
def horizontal_angle(C, P):
"""Return the angle to the horizontal for the connection from C to P.
This uses the arcus sine function and resolves its inherent ambiguity by
looking up in which quadrant vector S = P - C is located.
"""
S = Point(P - C).unit # unit vector 'C' -> 'P'
alfa = math.asin(abs(S.y)) # absolute angle from horizontal
if S.x < 0: # make arcsin result unique
if S.y <= 0: # bottom-left
alfa = -(math.pi - alfa)
else: # top-left
alfa = math.pi - alfa
else:
if S.y >= 0: # top-right
pass
else: # bottom-right
alfa = -alfa
return alfa
def insert_text(
self,
point: point_like,
buffer_: typing.Union[str, list],
fontsize: float = 11,
lineheight: OptFloat = None,
fontname: str = "helv",
fontfile: OptStr = None,
set_simple: bool = 0,
encoding: int = 0,
color: OptSeq = None,
fill: OptSeq = None,
render_mode: int = 0,
border_width: float = 1,
rotate: int = 0,
morph: OptSeq = None,
stroke_opacity: float = 1,
fill_opacity: float = 1,
oc: int = 0,
) -> int:
# ensure 'text' is a list of strings, worth dealing with
if not bool(buffer_):
return 0
if type(buffer_) not in (list, tuple):
text = buffer_.splitlines()
else:
text = buffer_
if not len(text) > 0:
return 0
point = Point(point)
try:
maxcode = max([ord(c) for c in " ".join(text)])
except Exception:
exception_info()
return 0
# ensure valid 'fontname'
fname = fontname
if fname.startswith("/"):
fname = fname[1:]
xref = self.page.insert_font(
fontname=fname,
fontfile=fontfile,
encoding=encoding,
set_simple=set_simple,
)
fontinfo = CheckFontInfo(self.doc, xref)
fontdict = fontinfo[1]
ordering = fontdict["ordering"]
simple = fontdict["simple"]
bfname = fontdict["name"]
ascender = fontdict["ascender"]
descender = fontdict["descender"]
if lineheight:
lheight = fontsize * lineheight
elif ascender - descender <= 1:
lheight = fontsize * 1.2
else:
lheight = fontsize * (ascender - descender)
if maxcode > 255:
glyphs = self.doc.get_char_widths(xref, maxcode + 1)
else:
glyphs = fontdict["glyphs"]
tab = []
for t in text:
if simple and bfname not in ("Symbol", "ZapfDingbats"):
g = None
else:
g = glyphs
tab.append(getTJstr(t, g, simple, ordering))
text = tab
color_str = ColorCode(color, "c")
fill_str = ColorCode(fill, "f")
if not fill and render_mode == 0: # ensure fill color when 0 Tr
fill = color
fill_str = ColorCode(color, "f")
morphing = CheckMorph(morph)
rot = rotate
if rot % 90 != 0:
raise ValueError("bad rotate value")
while rot < 0:
rot += 360
rot = rot % 360 # text rotate = 0, 90, 270, 180
templ1 = lambda a, b, c, d, e, f, g: f"\nq\n{a}{b}BT\n%{c}1 0 0 1 {_format_g((d, e))} Tm\n/{f} {g} Tf "
templ2 = lambda a: f"TJ\n0 -{_format_g(a)} TD\n"
cmp90 = "0 1 -1 0 0 0 cm\n" # rotates 90 deg counter-clockwise
cmm90 = "0 -1 1 0 0 0 cm\n" # rotates 90 deg clockwise
cm180 = "-1 0 0 -1 0 0 cm\n" # rotates by 180 deg.
height = self.height
width = self.width
# setting up for standard rotation directions
# case rotate = 0
if morphing:
m1 = Matrix(1, 0, 0, 1, morph[0].x + self.x, height - morph[0].y - self.y)
mat = ~m1 * morph[1] * m1
cm = _format_g(JM_TUPLE(mat)) + " cm\n"
else:
cm = ""
top = height - point.y - self.y # start of 1st char
left = point.x + self.x # start of 1. char
space = top # space available
if rot == 90:
left = height - point.y - self.y
top = -point.x - self.x
cm += cmp90
space = width - abs(top)
elif rot == 270:
left = -height + point.y + self.y
top = point.x + self.x
cm += cmm90
space = abs(top)
elif rot == 180:
left = -point.x - self.x
top = -height + point.y + self.y
cm += cm180
space = abs(point.y + self.y)
optcont = self.page._get_optional_content(oc)
if optcont is not None:
bdc = "/OC /%s BDC\n" % optcont
emc = "EMC\n"
else:
bdc = emc = ""
alpha = self.page._set_opacity(CA=stroke_opacity, ca=fill_opacity)
if alpha is None:
alpha = ""
else:
alpha = "/%s gs\n" % alpha
nres = templ1(bdc, alpha, cm, left, top, fname, fontsize)
if render_mode > 0:
nres += "%i Tr " % render_mode
if border_width != 1:
nres += _format_g(border_width) + " w "
if color is not None:
nres += color_str
if fill is not None:
nres += fill_str
# =========================================================================
# start text insertion
# =========================================================================
nres += text[0]
nlines = 1 # set output line counter
if len(text) > 1:
nres += templ2(lheight) # line 1
else:
nres += 'TJ'
for i in range(1, len(text)):
if space < lheight:
break # no space left on page
if i > 1:
nres += "\nT* "
nres += text[i] + 'TJ'
space -= lheight
nlines += 1
nres += "\nET\n%sQ\n" % emc
# =========================================================================
# end of text insertion
# =========================================================================
# update the /Contents object
self.text_cont += nres
return nlines
def update_rect(self, x):
if self.rect is None:
if len(x) == 2:
self.rect = Rect(x, x)
else:
self.rect = Rect(x)
else:
if len(x) == 2:
x = Point(x)
self.rect.x0 = min(self.rect.x0, x.x)
self.rect.y0 = min(self.rect.y0, x.y)
self.rect.x1 = max(self.rect.x1, x.x)
self.rect.y1 = max(self.rect.y1, x.y)
else:
x = Rect(x)
self.rect.x0 = min(self.rect.x0, x.x0)
self.rect.y0 = min(self.rect.y0, x.y0)
self.rect.x1 = max(self.rect.x1, x.x1)
self.rect.y1 = max(self.rect.y1, x.y1)
class Story:
def __init__( self, html='', user_css=None, em=12, archive=None):
buffer_ = mupdf.fz_new_buffer_from_copied_data( html.encode('utf-8'))
if archive and not isinstance(archive, Archive):
archive = Archive(archive)
arch = archive.this if archive else mupdf.FzArchive( None)
if hasattr(mupdf, 'FzStoryS'):
self.this = mupdf.FzStoryS( buffer_, user_css, em, arch)
else:
self.this = mupdf.FzStory( buffer_, user_css, em, arch)
def add_header_ids(self):
'''
Look for `<h1..6>` items in `self` and adds unique `id`
attributes if not already present.
'''
dom = self.body
i = 0
x = dom.find(None, None, None)
while x:
name = x.tagname
if len(name) == 2 and name[0]=="h" and name[1] in "123456":
attr = x.get_attribute_value("id")
if not attr:
id_ = f"h_id_{i}"
#log(f"{name=}: setting {id_=}")
x.set_attribute("id", id_)
i += 1
x = x.find_next(None, None, None)
@staticmethod
def add_pdf_links(document_or_stream, positions):
"""
Adds links to PDF document.
Args:
document_or_stream:
A PDF `Document` or raw PDF content, for example an
`io.BytesIO` instance.
positions:
List of `ElementPosition`'s for `document_or_stream`,
typically from Story.element_positions(). We raise an
exception if two or more positions have same id.
Returns:
`document_or_stream` if a `Document` instance, otherwise a
new `Document` instance.
We raise an exception if an `href` in `positions` refers to an
internal position `#<name>` but no item in `positions` has `id =
name`.
"""
if isinstance(document_or_stream, Document):
document = document_or_stream
else:
document = Document("pdf", document_or_stream)
# Create dict from id to position, which we will use to find
# link destinations.
#
id_to_position = dict()
#log(f"positions: {positions}")
for position in positions:
#log(f"add_pdf_links(): position: {position}")
if (position.open_close & 1) and position.id:
#log(f"add_pdf_links(): position with id: {position}")
if position.id in id_to_position:
#log(f"Ignoring duplicate positions with id={position.id!r}")
pass
else:
id_to_position[ position.id] = position
# Insert links for all positions that have an `href`.
#
for position_from in positions:
if (position_from.open_close & 1) and position_from.href:
#log(f"add_pdf_links(): position with href: {position}")
link = dict()
link['from'] = Rect(position_from.rect)
if position_from.href.startswith("#"):
#`<a href="#...">...</a>` internal link.
target_id = position_from.href[1:]
try:
position_to = id_to_position[ target_id]
except Exception as e:
if g_exceptions_verbose > 1: exception_info()
raise RuntimeError(f"No destination with id={target_id}, required by position_from: {position_from}") from e
# Make link from `position_from`'s rect to top-left of
# `position_to`'s rect.
if 0:
log(f"add_pdf_links(): making link from:")
log(f"add_pdf_links(): {position_from}")
log(f"add_pdf_links(): to:")
log(f"add_pdf_links(): {position_to}")
link["kind"] = LINK_GOTO
x0, y0, x1, y1 = position_to.rect
# This appears to work well with viewers which scroll
# to make destination point top-left of window.
link["to"] = Point(x0, y0)
link["page"] = position_to.page_num - 1
else:
# `<a href="...">...</a>` external link.
if position_from.href.startswith('name:'):
link['kind'] = LINK_NAMED
link['name'] = position_from.href[5:]
else:
link['kind'] = LINK_URI
link['uri'] = position_from.href
#log(f'Adding link: {position_from.page_num=} {link=}.')
document[position_from.page_num - 1].insert_link(link)
return document
@property
def body(self):
dom = self.document()
return dom.bodytag()
def document( self):
dom = mupdf.fz_story_document( self.this)
return Xml( dom)
def draw( self, device, matrix=None):
ctm2 = JM_matrix_from_py( matrix)
dev = device.this if device else mupdf.FzDevice( None)
mupdf.fz_draw_story( self.this, dev, ctm2)
def element_positions( self, function, args=None):
'''
Trigger a callback function to record where items have been placed.
'''
if type(args) is dict:
for k in args.keys():
if not (type(k) is str and k.isidentifier()):
raise ValueError(f"invalid key '{k}'")
else:
args = {}
if not callable(function) or function.__code__.co_argcount != 1:
raise ValueError("callback 'function' must be a callable with exactly one argument")
def function2( position):
class Position2:
pass
position2 = Position2()
position2.depth = position.depth
position2.heading = position.heading
position2.id = position.id
position2.rect = JM_py_from_rect(position.rect)
position2.text = position.text
position2.open_close = position.open_close
position2.rect_num = position.rectangle_num
position2.href = position.href
if args:
for k, v in args.items():
setattr( position2, k, v)
function( position2)
mupdf.fz_story_positions( self.this, function2)
def place( self, where):
where = JM_rect_from_py( where)
filled = mupdf.FzRect()
more = mupdf.fz_place_story( self.this, where, filled)
return more, JM_py_from_rect( filled)
def reset( self):
mupdf.fz_reset_story( self.this)
def write(self, writer, rectfn, positionfn=None, pagefn=None):
dev = None
page_num = 0
rect_num = 0
filled = Rect(0, 0, 0, 0)
while 1:
mediabox, rect, ctm = rectfn(rect_num, filled)
rect_num += 1
if mediabox:
# new page.
page_num += 1
more, filled = self.place( rect)
if positionfn:
def positionfn2(position):
# We add a `.page_num` member to the
# `ElementPosition` instance.
position.page_num = page_num
positionfn(position)
self.element_positions(positionfn2)
if writer:
if mediabox:
# new page.
if dev:
if pagefn:
pagefn(page_num, mediabox, dev, 1)
writer.end_page()
dev = writer.begin_page( mediabox)
if pagefn:
pagefn(page_num, mediabox, dev, 0)
self.draw( dev, ctm)
if not more:
if pagefn:
pagefn( page_num, mediabox, dev, 1)
writer.end_page()
else:
self.draw(None, ctm)
if not more:
break
@staticmethod
def write_stabilized(writer, contentfn, rectfn, user_css=None, em=12, positionfn=None, pagefn=None, archive=None, add_header_ids=True):
positions = list()
content = None
# Iterate until stable.
while 1:
content_prev = content
content = contentfn( positions)
stable = False
if content == content_prev:
stable = True
content2 = content
story = Story(content2, user_css, em, archive)
if add_header_ids:
story.add_header_ids()
positions = list()
def positionfn2(position):
#log(f"write_stabilized(): {stable=} {positionfn=} {position=}")
positions.append(position)
if stable and positionfn:
positionfn(position)
story.write(
writer if stable else None,
rectfn,
positionfn2,
pagefn,
)
if stable:
break
@staticmethod
def write_stabilized_with_links(contentfn, rectfn, user_css=None, em=12, positionfn=None, pagefn=None, archive=None, add_header_ids=True):
#log("write_stabilized_with_links()")
stream = io.BytesIO()
writer = DocumentWriter(stream)
positions = []
def positionfn2(position):
#log(f"write_stabilized_with_links(): {position=}")
positions.append(position)
if positionfn:
positionfn(position)
Story.write_stabilized(writer, contentfn, rectfn, user_css, em, positionfn2, pagefn, archive, add_header_ids)
writer.close()
stream.seek(0)
return Story.add_pdf_links(stream, positions)
def write_with_links(self, rectfn, positionfn=None, pagefn=None):
#log("write_with_links()")
stream = io.BytesIO()
writer = DocumentWriter(stream)
positions = []
def positionfn2(position):
#log(f"write_with_links(): {position=}")
positions.append(position)
if positionfn:
positionfn(position)
self.write(writer, rectfn, positionfn=positionfn2, pagefn=pagefn)
writer.close()
stream.seek(0)
return Story.add_pdf_links(stream, positions)
class FitResult:
'''
The result from a `Story.fit*()` method.
Members:
`big_enough`:
`True` if the fit succeeded.
`filled`:
From the last call to `Story.place()`.
`more`:
`False` if the fit succeeded.
`numcalls`:
Number of calls made to `self.place()`.
`parameter`:
The successful parameter value, or the largest failing value.
`rect`:
The rect created from `parameter`.
'''
def __init__(self, big_enough=None, filled=None, more=None, numcalls=None, parameter=None, rect=None):
self.big_enough = big_enough
self.filled = filled
self.more = more
self.numcalls = numcalls
self.parameter = parameter
self.rect = rect
def __repr__(self):
return (
f' big_enough={self.big_enough}'
f' filled={self.filled}'
f' more={self.more}'
f' numcalls={self.numcalls}'
f' parameter={self.parameter}'
f' rect={self.rect}'
)
def fit(self, fn, pmin=None, pmax=None, delta=0.001, verbose=False):
'''
Finds optimal rect that contains the story `self`.
Returns a `Story.FitResult` instance.
On success, the last call to `self.place()` will have been with the
returned rectangle, so `self.draw()` can be used directly.
Args:
:arg fn:
A callable taking a floating point `parameter` and returning a
`pymupdf.Rect()`. If the rect is empty, we assume the story will
not fit and do not call `self.place()`.
Must guarantee that `self.place()` behaves monotonically when
given rect `fn(parameter`) as `parameter` increases. This
usually means that both width and height increase or stay
unchanged as `parameter` increases.
:arg pmin:
Minimum parameter to consider; `None` for -infinity.
:arg pmax:
Maximum parameter to consider; `None` for +infinity.
:arg delta:
Maximum error in returned `parameter`.
:arg verbose:
If true we output diagnostics.
'''
def log(text):
assert verbose
message(f'fit(): {text}')
assert isinstance(pmin, (int, float)) or pmin is None
assert isinstance(pmax, (int, float)) or pmax is None
class State:
def __init__(self):
self.pmin = pmin
self.pmax = pmax
self.pmin_result = None
self.pmax_result = None
self.result = None
self.numcalls = 0
if verbose:
self.pmin0 = pmin
self.pmax0 = pmax
state = State()
if verbose:
log(f'starting. {state.pmin=} {state.pmax=}.')
self.reset()
def ret():
if state.pmax is not None:
if state.last_p != state.pmax:
if verbose:
log(f'Calling update() with pmax, because was overwritten by later calls.')
big_enough = update(state.pmax)
assert big_enough
result = state.pmax_result
else:
result = state.pmin_result if state.pmin_result else Story.FitResult(numcalls=state.numcalls)
if verbose:
log(f'finished. {state.pmin0=} {state.pmax0=} {state.pmax=}: returning {result=}')
return result
def update(parameter):
'''
Evaluates `more, _ = self.place(fn(parameter))`. If `more` is
false, then `rect` is big enough to contain `self` and we
set `state.pmax=parameter` and return True. Otherwise we set
`state.pmin=parameter` and return False.
'''
rect = fn(parameter)
assert isinstance(rect, Rect), f'{type(rect)=} {rect=}'
if rect.is_empty:
big_enough = False
result = Story.FitResult(parameter=parameter, numcalls=state.numcalls)
if verbose:
log(f'update(): not calling self.place() because rect is empty.')
else:
more, filled = self.place(rect)
state.numcalls += 1
big_enough = not more
result = Story.FitResult(
filled=filled,
more=more,
numcalls=state.numcalls,
parameter=parameter,
rect=rect,
big_enough=big_enough,
)
if verbose:
log(f'update(): called self.place(): {state.numcalls:>2d}: {more=} {parameter=} {rect=}.')
if big_enough:
state.pmax = parameter
state.pmax_result = result
else:
state.pmin = parameter
state.pmin_result = result
state.last_p = parameter
return big_enough
def opposite(p, direction):
'''
Returns same sign as `direction`, larger or smaller than `p` if
direction is positive or negative respectively.
'''
if p is None or p==0:
return direction
if direction * p > 0:
return 2 * p
return -p
if state.pmin is None:
# Find an initial finite pmin value.
if verbose: log(f'finding pmin.')
parameter = opposite(state.pmax, -1)
while 1:
if not update(parameter):
break
parameter *= 2
else:
if update(state.pmin):
if verbose: log(f'{state.pmin=} is big enough.')
return ret()
if state.pmax is None:
# Find an initial finite pmax value.
if verbose: log(f'finding pmax.')
parameter = opposite(state.pmin, +1)
while 1:
if update(parameter):
break
parameter *= 2
else:
if not update(state.pmax):
# No solution possible.
state.pmax = None
if verbose: log(f'No solution possible {state.pmax=}.')
return ret()
# Do binary search in pmin..pmax.
if verbose: log(f'doing binary search with {state.pmin=} {state.pmax=}.')
while 1:
if state.pmax - state.pmin < delta:
return ret()
parameter = (state.pmin + state.pmax) / 2
update(parameter)
def fit_scale(self, rect, scale_min=0, scale_max=None, delta=0.001, verbose=False):
'''
Finds smallest value `scale` in range `scale_min..scale_max` where
`scale * rect` is large enough to contain the story `self`.
Returns a `Story.FitResult` instance.
:arg width:
width of rect.
:arg height:
height of rect.
:arg scale_min:
Minimum scale to consider; must be >= 0.
:arg scale_max:
Maximum scale to consider, must be >= scale_min or `None` for
infinite.
:arg delta:
Maximum error in returned scale.
:arg verbose:
If true we output diagnostics.
'''
x0, y0, x1, y1 = rect
width = x1 - x0
height = y1 - y0
def fn(scale):
return Rect(x0, y0, x0 + scale*width, y0 + scale*height)
return self.fit(fn, scale_min, scale_max, delta, verbose)
def fit_height(self, width, height_min=0, height_max=None, origin=(0, 0), delta=0.001, verbose=False):
'''
Finds smallest height in range `height_min..height_max` where a rect
with size `(width, height)` is large enough to contain the story
`self`.
Returns a `Story.FitResult` instance.
:arg width:
width of rect.
:arg height_min:
Minimum height to consider; must be >= 0.
:arg height_max:
Maximum height to consider, must be >= height_min or `None` for
infinite.
:arg origin:
`(x0, y0)` of rect.
:arg delta:
Maximum error in returned height.
:arg verbose:
If true we output diagnostics.
'''
x0, y0 = origin
x1 = x0 + width
def fn(height):
return Rect(x0, y0, x1, y0+height)
return self.fit(fn, height_min, height_max, delta, verbose)
def fit_width(self, height, width_min=0, width_max=None, origin=(0, 0), delta=0.001, verbose=False):
'''
Finds smallest width in range `width_min..width_max` where a rect with size
`(width, height)` is large enough to contain the story `self`.
Returns a `Story.FitResult` instance.
Returns a `FitResult` instance.
:arg height:
height of rect.
:arg width_min:
Minimum width to consider; must be >= 0.
:arg width_max:
Maximum width to consider, must be >= width_min or `None` for
infinite.
:arg origin:
`(x0, y0)` of rect.
:arg delta:
Maximum error in returned width.
:arg verbose:
If true we output diagnostics.
'''
x0, y0 = origin
y1 = y0 + height
def fn(width):
return Rect(x0, y0, x0+width, y1)
return self.fit(fn, width_min, width_max, delta, verbose)
class TextPage:
def __init__(self, *args):
if args_match(args, mupdf.FzRect):
mediabox = args[0]
self.this = mupdf.FzStextPage( mediabox)
elif args_match(args, mupdf.FzStextPage):
self.this = args[0]
else:
raise Exception(f'Unrecognised args: {args}')
self.thisown = True
self.parent = None
def _extractText(self, format_):
this_tpage = self.this
res = mupdf.fz_new_buffer(1024)
out = mupdf.FzOutput( res)
# fixme: mupdfwrap.py thinks fz_output is not copyable, possibly
# because there is no .refs member visible and no fz_keep_output() fn,
# although there is an fz_drop_output(). So mupdf.fz_new_output_with_buffer()
# doesn't convert the returned fz_output* into a mupdf.FzOutput.
#out = mupdf.FzOutput(out)
if format_ == 1:
mupdf.fz_print_stext_page_as_html(out, this_tpage, 0)
elif format_ == 3:
mupdf.fz_print_stext_page_as_xml(out, this_tpage, 0)
elif format_ == 4:
mupdf.fz_print_stext_page_as_xhtml(out, this_tpage, 0)
else:
JM_print_stext_page_as_text(res, this_tpage)
out.fz_close_output()
text = JM_EscapeStrFromBuffer(res)
return text
def _getNewBlockList(self, page_dict, raw):
JM_make_textpage_dict(self.this, page_dict, raw)
def _textpage_dict(self, raw=False):
page_dict = {"width": self.rect.width, "height": self.rect.height}
self._getNewBlockList(page_dict, raw)
return page_dict
def extractBLOCKS(self):
"""Return a list with text block information."""
if g_use_extra:
return extra.extractBLOCKS(self.this)
block_n = -1
this_tpage = self.this
tp_rect = mupdf.FzRect(this_tpage.m_internal.mediabox)
res = mupdf.fz_new_buffer(1024)
lines = []
for block in this_tpage:
block_n += 1
blockrect = mupdf.FzRect(mupdf.FzRect.Fixed_EMPTY)
if block.m_internal.type == mupdf.FZ_STEXT_BLOCK_TEXT:
mupdf.fz_clear_buffer(res) # set text buffer to empty
line_n = -1
last_char = 0
for line in block:
line_n += 1
linerect = mupdf.FzRect(mupdf.FzRect.Fixed_EMPTY)
for ch in line:
cbbox = JM_char_bbox(line, ch)
if (not JM_rects_overlap(tp_rect, cbbox)
and not mupdf.fz_is_infinite_rect(tp_rect)
):
continue
JM_append_rune(res, ch.m_internal.c)
last_char = ch.m_internal.c
linerect = mupdf.fz_union_rect(linerect, cbbox)
if last_char != 10 and not mupdf.fz_is_empty_rect(linerect):
mupdf.fz_append_byte(res, 10)
blockrect = mupdf.fz_union_rect(blockrect, linerect)
text = JM_EscapeStrFromBuffer(res)
elif (JM_rects_overlap(tp_rect, block.m_internal.bbox)
or mupdf.fz_is_infinite_rect(tp_rect)
):
img = block.i_image()
cs = img.colorspace()
text = "<image: %s, width: %d, height: %d, bpc: %d>" % (
mupdf.fz_colorspace_name(cs),
img.w(), img.h(), img.bpc()
)
blockrect = mupdf.fz_union_rect(blockrect, mupdf.FzRect(block.m_internal.bbox))
if not mupdf.fz_is_empty_rect(blockrect):
litem = (
blockrect.x0,
blockrect.y0,
blockrect.x1,
blockrect.y1,
text,
block_n,
block.m_internal.type,
)
lines.append(litem)
return lines
def extractDICT(self, cb=None, sort=False) -> dict:
"""Return page content as a Python dict of images and text spans."""
val = self._textpage_dict(raw=False)
if cb is not None:
val["width"] = cb.width
val["height"] = cb.height
if sort is True:
blocks = val["blocks"]
blocks.sort(key=lambda b: (b["bbox"][3], b["bbox"][0]))
val["blocks"] = blocks
return val
def extractHTML(self) -> str:
"""Return page content as a HTML string."""
return self._extractText(1)
def extractIMGINFO(self, hashes=0):
"""Return a list with image meta information."""
block_n = -1
this_tpage = self.this
rc = []
for block in this_tpage:
block_n += 1
if block.m_internal.type == mupdf.FZ_STEXT_BLOCK_TEXT:
continue
img = block.i_image()
img_size = 0
if mupdf_version_tuple >= (1, 24):
compr_buff = mupdf.fz_compressed_image_buffer(img)
if compr_buff.m_internal:
img_size = compr_buff.fz_compressed_buffer_size()
compr_buff = None
else:
compr_buff = mupdf.ll_fz_compressed_image_buffer(img.m_internal)
if compr_buff:
img_size = mupdf.ll_fz_compressed_buffer_size(compr_buff)
if hashes:
r = mupdf.FzIrect(FZ_MIN_INF_RECT, FZ_MIN_INF_RECT, FZ_MAX_INF_RECT, FZ_MAX_INF_RECT)
assert mupdf.fz_is_infinite_irect(r)
m = mupdf.FzMatrix(img.w(), 0, 0, img.h(), 0, 0)
pix, w, h = mupdf.fz_get_pixmap_from_image(img, r, m)
digest = mupdf.fz_md5_pixmap2(pix)
digest = bytes(digest)
if img_size == 0:
img_size = img.w() * img.h() * img.n()
cs = mupdf.FzColorspace(mupdf.ll_fz_keep_colorspace(img.m_internal.colorspace))
block_dict = dict()
block_dict[ dictkey_number] = block_n
block_dict[ dictkey_bbox] = JM_py_from_rect(block.m_internal.bbox)
block_dict[ dictkey_matrix] = JM_py_from_matrix(block.i_transform())
block_dict[ dictkey_width] = img.w()
block_dict[ dictkey_height] = img.h()
block_dict[ dictkey_colorspace] = mupdf.fz_colorspace_n(cs)
block_dict[ dictkey_cs_name] = mupdf.fz_colorspace_name(cs)
block_dict[ dictkey_xres] = img.xres()
block_dict[ dictkey_yres] = img.yres()
block_dict[ dictkey_bpc] = img.bpc()
block_dict[ dictkey_size] = img_size
if hashes:
block_dict[ "digest"] = digest
rc.append(block_dict)
return rc
def extractJSON(self, cb=None, sort=False) -> str:
"""Return 'extractDICT' converted to JSON format."""
import base64
import json
val = self._textpage_dict(raw=False)
class b64encode(json.JSONEncoder):
def default(self, s):
if type(s) in (bytes, bytearray):
return base64.b64encode(s).decode()
if cb is not None:
val["width"] = cb.width
val["height"] = cb.height
if sort is True:
blocks = val["blocks"]
blocks.sort(key=lambda b: (b["bbox"][3], b["bbox"][0]))
val["blocks"] = blocks
val = json.dumps(val, separators=(",", ":"), cls=b64encode, indent=1)
return val
def extractRAWDICT(self, cb=None, sort=False) -> dict:
"""Return page content as a Python dict of images and text characters."""
val = self._textpage_dict(raw=True)
if cb is not None:
val["width"] = cb.width
val["height"] = cb.height
if sort is True:
blocks = val["blocks"]
blocks.sort(key=lambda b: (b["bbox"][3], b["bbox"][0]))
val["blocks"] = blocks
return val
def extractRAWJSON(self, cb=None, sort=False) -> str:
"""Return 'extractRAWDICT' converted to JSON format."""
import base64
import json
val = self._textpage_dict(raw=True)
class b64encode(json.JSONEncoder):
def default(self,s):
if type(s) in (bytes, bytearray):
return base64.b64encode(s).decode()
if cb is not None:
val["width"] = cb.width
val["height"] = cb.height
if sort is True:
blocks = val["blocks"]
blocks.sort(key=lambda b: (b["bbox"][3], b["bbox"][0]))
val["blocks"] = blocks
val = json.dumps(val, separators=(",", ":"), cls=b64encode, indent=1)
return val
def extractSelection(self, pointa, pointb):
a = JM_point_from_py(pointa)
b = JM_point_from_py(pointb)
found = mupdf.fz_copy_selection(self.this, a, b, 0)
return found
def extractText(self, sort=False) -> str:
"""Return simple, bare text on the page."""
if sort is False:
return self._extractText(0)
blocks = self.extractBLOCKS()[:]
blocks.sort(key=lambda b: (b[3], b[0]))
return "".join([b[4] for b in blocks])
def extractTextbox(self, rect):
this_tpage = self.this
assert isinstance(this_tpage, mupdf.FzStextPage)
area = JM_rect_from_py(rect)
found = JM_copy_rectangle(this_tpage, area)
rc = PyUnicode_DecodeRawUnicodeEscape(found)
return rc
def extractWORDS(self, delimiters=None):
"""Return a list with text word information."""
if g_use_extra:
return extra.extractWORDS(self.this, delimiters)
buflen = 0
block_n = -1
wbbox = mupdf.FzRect(mupdf.FzRect.Fixed_EMPTY) # word bbox
this_tpage = self.this
tp_rect = mupdf.FzRect(this_tpage.m_internal.mediabox)
lines = None
buff = mupdf.fz_new_buffer(64)
lines = []
for block in this_tpage:
block_n += 1
if block.m_internal.type != mupdf.FZ_STEXT_BLOCK_TEXT:
continue
line_n = -1
for line in block:
line_n += 1
word_n = 0 # word counter per line
mupdf.fz_clear_buffer(buff) # reset word buffer
buflen = 0 # reset char counter
for ch in line:
cbbox = JM_char_bbox(line, ch)
if (not JM_rects_overlap(tp_rect, cbbox)
and not mupdf.fz_is_infinite_rect(tp_rect)
):
continue
word_delimiter = JM_is_word_delimiter(ch.m_internal.c, delimiters)
if word_delimiter:
if buflen == 0:
continue # skip delimiters at line start
if not mupdf.fz_is_empty_rect(wbbox):
word_n, wbbox = JM_append_word(lines, buff, wbbox, block_n, line_n, word_n)
mupdf.fz_clear_buffer(buff)
buflen = 0 # reset char counter
continue
# append one unicode character to the word
JM_append_rune(buff, ch.m_internal.c)
buflen += 1
# enlarge word bbox
wbbox = mupdf.fz_union_rect(wbbox, JM_char_bbox(line, ch))
if buflen and not mupdf.fz_is_empty_rect(wbbox):
word_n, wbbox = JM_append_word(lines, buff, wbbox, block_n, line_n, word_n)
buflen = 0
return lines
def extractXHTML(self) -> str:
"""Return page content as a XHTML string."""
return self._extractText(4)
def extractXML(self) -> str:
"""Return page content as a XML string."""
return self._extractText(3)
def poolsize(self):
"""TextPage current poolsize."""
tpage = self.this
pool = mupdf.Pool(tpage.m_internal.pool)
size = mupdf.fz_pool_size( pool)
pool.m_internal = None # Ensure that pool's destructor does not free the pool.
return size
@property
def rect(self):
"""Page rectangle."""
this_tpage = self.this
mediabox = this_tpage.m_internal.mediabox
val = JM_py_from_rect(mediabox)
val = Rect(val)
return val
def search(self, needle, hit_max=0, quads=1):
"""Locate 'needle' returning rects or quads."""
val = JM_search_stext_page(self.this, needle)
if not val:
return val
items = len(val)
for i in range(items): # change entries to quads or rects
q = Quad(val[i])
if quads:
val[i] = q
else:
val[i] = q.rect
if quads:
return val
i = 0 # join overlapping rects on the same line
while i < items - 1:
v1 = val[i]
v2 = val[i + 1]
if v1.y1 != v2.y1 or (v1 & v2).is_empty:
i += 1
continue # no overlap on same line
val[i] = v1 | v2 # join rectangles
del val[i + 1] # remove v2
items -= 1 # reduce item count
return val
extractTEXT = extractText
class TextWriter:
def __init__(self, page_rect, opacity=1, color=None):
"""Stores text spans for later output on compatible PDF pages."""
self.this = mupdf.fz_new_text()
self.opacity = opacity
self.color = color
self.rect = Rect(page_rect)
self.ctm = Matrix(1, 0, 0, -1, 0, self.rect.height)
self.ictm = ~self.ctm
self.last_point = Point()
self.last_point.__doc__ = "Position following last text insertion."
self.text_rect = Rect()
self.text_rect.__doc__ = "Accumulated area of text spans."
self.used_fonts = set()
self.thisown = True
@property
def _bbox(self):
val = JM_py_from_rect( mupdf.fz_bound_text( self.this, mupdf.FzStrokeState(None), mupdf.FzMatrix()))
val = Rect(val)
return val
def append(self, pos, text, font=None, fontsize=11, language=None, right_to_left=0, small_caps=0):
"""Store 'text' at point 'pos' using 'font' and 'fontsize'."""
pos = Point(pos) * self.ictm
#log( '{font=}')
if font is None:
font = Font("helv")
if not font.is_writable:
if 0:
log( '{font.this.m_internal.name=}')
log( '{font.this.m_internal.t3matrix=}')
log( '{font.this.m_internal.bbox=}')
log( '{font.this.m_internal.glyph_count=}')
log( '{font.this.m_internal.use_glyph_bbox=}')
log( '{font.this.m_internal.width_count=}')
log( '{font.this.m_internal.width_default=}')
log( '{font.this.m_internal.has_digest=}')
log( 'Unsupported font {font.name=}')
if mupdf_cppyy:
import cppyy
log( f'Unsupported font {cppyy.gbl.mupdf_font_name(font.this.m_internal)=}')
raise ValueError("Unsupported font '%s'." % font.name)
if right_to_left:
text = self.clean_rtl(text)
text = "".join(reversed(text))
right_to_left = 0
lang = mupdf.fz_text_language_from_string(language)
p = JM_point_from_py(pos)
trm = mupdf.fz_make_matrix(fontsize, 0, 0, fontsize, p.x, p.y)
markup_dir = 0
wmode = 0
if small_caps == 0:
trm = mupdf.fz_show_string( self.this, font.this, trm, text, wmode, right_to_left, markup_dir, lang)
else:
trm = JM_show_string_cs( self.this, font.this, trm, text, wmode, right_to_left, markup_dir, lang)
val = JM_py_from_matrix(trm)
self.last_point = Point(val[-2:]) * self.ctm
self.text_rect = self._bbox * self.ctm
val = self.text_rect, self.last_point
if font.flags["mono"] == 1:
self.used_fonts.add(font)
return val
def appendv(self, pos, text, font=None, fontsize=11, language=None, small_caps=False):
lheight = fontsize * 1.2
for c in text:
self.append(pos, c, font=font, fontsize=fontsize,
language=language, small_caps=small_caps)
pos.y += lheight
return self.text_rect, self.last_point
def clean_rtl(self, text):
"""Revert the sequence of Latin text parts.
Text with right-to-left writing direction (Arabic, Hebrew) often
contains Latin parts, which are written in left-to-right: numbers, names,
etc. For output as PDF text we need *everything* in right-to-left.
E.g. an input like "<arabic> ABCDE FG HIJ <arabic> KL <arabic>" will be
converted to "<arabic> JIH GF EDCBA <arabic> LK <arabic>". The Arabic
parts remain untouched.
Args:
text: str
Returns:
Massaged string.
"""
if not text:
return text
# split into words at space boundaries
words = text.split(" ")
idx = []
for i in range(len(words)):
w = words[i]
# revert character sequence for Latin only words
if not (len(w) < 2 or max([ord(c) for c in w]) > 255):
words[i] = "".join(reversed(w))
idx.append(i) # stored index of Latin word
# adjacent Latin words must revert their sequence, too
idx2 = [] # store indices of adjacent Latin words
for i in range(len(idx)):
if idx2 == []: # empty yet?
idx2.append(idx[i]) # store Latin word number
elif idx[i] > idx2[-1] + 1: # large gap to last?
if len(idx2) > 1: # at least two consecutives?
words[idx2[0] : idx2[-1] + 1] = reversed(
words[idx2[0] : idx2[-1] + 1]
) # revert their sequence
idx2 = [idx[i]] # re-initialize
elif idx[i] == idx2[-1] + 1: # new adjacent Latin word
idx2.append(idx[i])
text = " ".join(words)
return text
def write_text(self, page, color=None, opacity=-1, overlay=1, morph=None, matrix=None, render_mode=0, oc=0):
"""Write the text to a PDF page having the TextWriter's page size.
Args:
page: a PDF page having same size.
color: override text color.
opacity: override transparency.
overlay: put in foreground or background.
morph: tuple(Point, Matrix), apply a matrix with a fixpoint.
matrix: Matrix to be used instead of 'morph' argument.
render_mode: (int) PDF render mode operator 'Tr'.
"""
CheckParent(page)
if abs(self.rect - page.rect) > 1e-3:
raise ValueError("incompatible page rect")
if morph is not None:
if (type(morph) not in (tuple, list)
or type(morph[0]) is not Point
or type(morph[1]) is not Matrix
):
raise ValueError("morph must be (Point, Matrix) or None")
if matrix is not None and morph is not None:
raise ValueError("only one of matrix, morph is allowed")
if getattr(opacity, "__float__", None) is None or opacity == -1:
opacity = self.opacity
if color is None:
color = self.color
if 1:
pdfpage = page._pdf_page()
alpha = 1
if opacity >= 0 and opacity < 1:
alpha = opacity
ncol = 1
dev_color = [0, 0, 0, 0]
if color:
ncol, dev_color = JM_color_FromSequence(color)
if ncol == 3:
colorspace = mupdf.fz_device_rgb()
elif ncol == 4:
colorspace = mupdf.fz_device_cmyk()
else:
colorspace = mupdf.fz_device_gray()
resources = mupdf.pdf_new_dict(pdfpage.doc(), 5)
contents = mupdf.fz_new_buffer(1024)
dev = mupdf.pdf_new_pdf_device( pdfpage.doc(), mupdf.FzMatrix(), resources, contents)
#log( '=== {dev_color!r=}')
mupdf.fz_fill_text(
dev,
self.this,
mupdf.FzMatrix(),
colorspace,
dev_color,
alpha,
mupdf.FzColorParams(mupdf.fz_default_color_params),
)
mupdf.fz_close_device( dev)
# copy generated resources into the one of the page
max_nums = JM_merge_resources( pdfpage, resources)
cont_string = JM_EscapeStrFromBuffer( contents)
result = (max_nums, cont_string)
val = result
max_nums = val[0]
content = val[1]
max_alp, max_font = max_nums
old_cont_lines = content.splitlines()
optcont = page._get_optional_content(oc)
if optcont is not None:
bdc = "/OC /%s BDC" % optcont
emc = "EMC"
else:
bdc = emc = ""
new_cont_lines = ["q"]
if bdc:
new_cont_lines.append(bdc)
cb = page.cropbox_position
if page.rotation in (90, 270):
delta = page.rect.height - page.rect.width
else:
delta = 0
mb = page.mediabox
if bool(cb) or mb.y0 != 0 or delta != 0:
new_cont_lines.append(f"1 0 0 1 {_format_g((cb.x, cb.y + mb.y0 - delta))} cm")
if morph:
p = morph[0] * self.ictm
delta = Matrix(1, 1).pretranslate(p.x, p.y)
matrix = ~delta * morph[1] * delta
if morph or matrix:
new_cont_lines.append(_format_g(JM_TUPLE(matrix)) + " cm")
for line in old_cont_lines:
if line.endswith(" cm"):
continue
if line == "BT":
new_cont_lines.append(line)
new_cont_lines.append("%i Tr" % render_mode)
continue
if line.endswith(" gs"):
alp = int(line.split()[0][4:]) + max_alp
line = "/Alp%i gs" % alp
elif line.endswith(" Tf"):
temp = line.split()
fsize = float(temp[1])
if render_mode != 0:
w = fsize * 0.05
else:
w = 1
new_cont_lines.append(_format_g(w) + " w")
font = int(temp[0][2:]) + max_font
line = " ".join(["/F%i" % font] + temp[1:])
elif line.endswith(" rg"):
new_cont_lines.append(line.replace("rg", "RG"))
elif line.endswith(" g"):
new_cont_lines.append(line.replace(" g", " G"))
elif line.endswith(" k"):
new_cont_lines.append(line.replace(" k", " K"))
new_cont_lines.append(line)
if emc:
new_cont_lines.append(emc)
new_cont_lines.append("Q\n")
content = "\n".join(new_cont_lines).encode("utf-8")
TOOLS._insert_contents(page, content, overlay=overlay)
val = None
for font in self.used_fonts:
repair_mono_font(page, font)
return val
class IRect:
"""
IRect() - all zeros
IRect(x0, y0, x1, y1) - 4 coordinates
IRect(top-left, x1, y1) - point and 2 coordinates
IRect(x0, y0, bottom-right) - 2 coordinates and point
IRect(top-left, bottom-right) - 2 points
IRect(sequ) - new from sequence or rect-like
"""
def __add__(self, p):
return Rect.__add__(self, p).round()
def __and__(self, x):
return Rect.__and__(self, x).round()
def __contains__(self, x):
return Rect.__contains__(self, x)
def __eq__(self, r):
if not hasattr(r, "__len__"):
return False
return len(r) == 4 and self.x0 == r[0] and self.y0 == r[1] and self.x1 == r[2] and self.y1 == r[3]
def __getitem__(self, i):
return (self.x0, self.y0, self.x1, self.y1)[i]
def __init__(self, *args, p0=None, p1=None, x0=None, y0=None, x1=None, y1=None):
self.x0, self.y0, self.x1, self.y1 = util_make_irect( *args, p0=p0, p1=p1, x0=x0, y0=y0, x1=x1, y1=y1)
def __len__(self):
return 4
def __mul__(self, m):
return Rect.__mul__(self, m).round()
def __neg__(self):
return IRect(-self.x0, -self.y0, -self.x1, -self.y1)
def __or__(self, x):
return Rect.__or__(self, x).round()
def __pos__(self):
return IRect(self)
def __repr__(self):
return "IRect" + str(tuple(self))
def __setitem__(self, i, v):
v = int(v)
if i == 0: self.x0 = v
elif i == 1: self.y0 = v
elif i == 2: self.x1 = v
elif i == 3: self.y1 = v
else:
raise IndexError("index out of range")
return None
def __sub__(self, p):
return Rect.__sub__(self, p).round()
def __truediv__(self, m):
return Rect.__truediv__(self, m).round()
@property
def bottom_left(self):
"""Bottom-left corner."""
return Point(self.x0, self.y1)
@property
def bottom_right(self):
"""Bottom-right corner."""
return Point(self.x1, self.y1)
@property
def height(self):
return max(0, self.y1 - self.y0)
def include_point(self, p):
"""Extend rectangle to include point p."""
rect = self.rect.include_point(p)
return rect.irect
def include_rect(self, r):
"""Extend rectangle to include rectangle r."""
rect = self.rect.include_rect(r)
return rect.irect
def intersect(self, r):
"""Restrict rectangle to intersection with rectangle r."""
return Rect.intersect(self, r).round()
def intersects(self, x):
return Rect.intersects(self, x)
@property
def is_empty(self):
"""True if rectangle area is empty."""
return self.x0 >= self.x1 or self.y0 >= self.y1
@property
def is_infinite(self):
"""True if rectangle is infinite."""
return self.x0 == self.y0 == FZ_MIN_INF_RECT and self.x1 == self.y1 == FZ_MAX_INF_RECT
@property
def is_valid(self):
"""True if rectangle is valid."""
return self.x0 <= self.x1 and self.y0 <= self.y1
def morph(self, p, m):
"""Morph with matrix-like m and point-like p.
Returns a new quad."""
if self.is_infinite:
return INFINITE_QUAD()
return self.quad.morph(p, m)
def norm(self):
return math.sqrt(sum([c*c for c in self]))
def normalize(self):
"""Replace rectangle with its valid version."""
if self.x1 < self.x0:
self.x0, self.x1 = self.x1, self.x0
if self.y1 < self.y0:
self.y0, self.y1 = self.y1, self.y0
return self
@property
def quad(self):
"""Return Quad version of rectangle."""
return Quad(self.tl, self.tr, self.bl, self.br)
@property
def rect(self):
return Rect(self)
@property
def top_left(self):
"""Top-left corner."""
return Point(self.x0, self.y0)
@property
def top_right(self):
"""Top-right corner."""
return Point(self.x1, self.y0)
def torect(self, r):
"""Return matrix that converts to target rect."""
r = Rect(r)
if self.is_infinite or self.is_empty or r.is_infinite or r.is_empty:
raise ValueError("rectangles must be finite and not empty")
return (
Matrix(1, 0, 0, 1, -self.x0, -self.y0)
* Matrix(r.width / self.width, r.height / self.height)
* Matrix(1, 0, 0, 1, r.x0, r.y0)
)
def transform(self, m):
return Rect.transform(self, m).round()
@property
def width(self):
return max(0, self.x1 - self.x0)
br = bottom_right
bl = bottom_left
tl = top_left
tr = top_right
# Data
#
if 1:
_self = sys.modules[__name__]
if 1:
for _name, _value in mupdf.__dict__.items():
if _name.startswith(('PDF_', 'UCDN_SCRIPT_')):
if _name.startswith('PDF_ENUM_NAME_'):
# Not a simple enum.
pass
else:
#assert not inspect.isroutine(value)
#log(f'importing {_name=} {_value=}.')
setattr(_self, _name, _value)
#log(f'{getattr( self, name, None)=}')
else:
# This is slow due to importing inspect, e.g. 0.019 instead of 0.004.
for _name, _value in inspect.getmembers(mupdf):
if _name.startswith(('PDF_', 'UCDN_SCRIPT_')):
if _name.startswith('PDF_ENUM_NAME_'):
# Not a simple enum.
pass
else:
#assert not inspect.isroutine(value)
#log(f'importing {name}')
setattr(_self, _name, _value)
#log(f'{getattr( self, name, None)=}')
# This is a macro so not preserved in mupdf C++/Python bindings.
#
PDF_SIGNATURE_DEFAULT_APPEARANCE = (0
| mupdf.PDF_SIGNATURE_SHOW_LABELS
| mupdf.PDF_SIGNATURE_SHOW_DN
| mupdf.PDF_SIGNATURE_SHOW_DATE
| mupdf.PDF_SIGNATURE_SHOW_TEXT_NAME
| mupdf.PDF_SIGNATURE_SHOW_GRAPHIC_NAME
| mupdf.PDF_SIGNATURE_SHOW_LOGO
)
#UCDN_SCRIPT_ADLAM = mupdf.UCDN_SCRIPT_ADLAM
#setattr(self, 'UCDN_SCRIPT_ADLAM', mupdf.UCDN_SCRIPT_ADLAM)
assert mupdf.UCDN_EAST_ASIAN_H == 1
# Flake8 incorrectly fails next two lines because we've dynamically added
# items to self.
assert PDF_TX_FIELD_IS_MULTILINE == mupdf.PDF_TX_FIELD_IS_MULTILINE # noqa: F821
assert UCDN_SCRIPT_ADLAM == mupdf.UCDN_SCRIPT_ADLAM # noqa: F821
del _self, _name, _value
_adobe_glyphs = {}
_adobe_unicodes = {}
AnyType = typing.Any
Base14_fontnames = (
"Courier",
"Courier-Oblique",
"Courier-Bold",
"Courier-BoldOblique",
"Helvetica",
"Helvetica-Oblique",
"Helvetica-Bold",
"Helvetica-BoldOblique",
"Times-Roman",
"Times-Italic",
"Times-Bold",
"Times-BoldItalic",
"Symbol",
"ZapfDingbats",
)
Base14_fontdict = {}
for f in Base14_fontnames:
Base14_fontdict[f.lower()] = f
Base14_fontdict["helv"] = "Helvetica"
Base14_fontdict["heit"] = "Helvetica-Oblique"
Base14_fontdict["hebo"] = "Helvetica-Bold"
Base14_fontdict["hebi"] = "Helvetica-BoldOblique"
Base14_fontdict["cour"] = "Courier"
Base14_fontdict["coit"] = "Courier-Oblique"
Base14_fontdict["cobo"] = "Courier-Bold"
Base14_fontdict["cobi"] = "Courier-BoldOblique"
Base14_fontdict["tiro"] = "Times-Roman"
Base14_fontdict["tibo"] = "Times-Bold"
Base14_fontdict["tiit"] = "Times-Italic"
Base14_fontdict["tibi"] = "Times-BoldItalic"
Base14_fontdict["symb"] = "Symbol"
Base14_fontdict["zadb"] = "ZapfDingbats"
EPSILON = 1e-5
FLT_EPSILON = 1e-5
# largest 32bit integers surviving C float conversion roundtrips
# used by MuPDF to define infinite rectangles
FZ_MIN_INF_RECT = -0x80000000
FZ_MAX_INF_RECT = 0x7fffff80
JM_annot_id_stem = "fitz"
JM_mupdf_warnings_store = []
JM_mupdf_show_errors = 1
JM_mupdf_show_warnings = 0
# ------------------------------------------------------------------------------
# Various PDF Optional Content Flags
# ------------------------------------------------------------------------------
PDF_OC_ON = 0
PDF_OC_TOGGLE = 1
PDF_OC_OFF = 2
# ------------------------------------------------------------------------------
# link kinds and link flags
# ------------------------------------------------------------------------------
LINK_NONE = 0
LINK_GOTO = 1
LINK_URI = 2
LINK_LAUNCH = 3
LINK_NAMED = 4
LINK_GOTOR = 5
LINK_FLAG_L_VALID = 1
LINK_FLAG_T_VALID = 2
LINK_FLAG_R_VALID = 4
LINK_FLAG_B_VALID = 8
LINK_FLAG_FIT_H = 16
LINK_FLAG_FIT_V = 32
LINK_FLAG_R_IS_ZOOM = 64
SigFlag_SignaturesExist = 1
SigFlag_AppendOnly = 2
STAMP_Approved = 0
STAMP_AsIs = 1
STAMP_Confidential = 2
STAMP_Departmental = 3
STAMP_Experimental = 4
STAMP_Expired = 5
STAMP_Final = 6
STAMP_ForComment = 7
STAMP_ForPublicRelease = 8
STAMP_NotApproved = 9
STAMP_NotForPublicRelease = 10
STAMP_Sold = 11
STAMP_TopSecret = 12
STAMP_Draft = 13
TEXT_ALIGN_LEFT = 0
TEXT_ALIGN_CENTER = 1
TEXT_ALIGN_RIGHT = 2
TEXT_ALIGN_JUSTIFY = 3
TEXT_FONT_SUPERSCRIPT = 1
TEXT_FONT_ITALIC = 2
TEXT_FONT_SERIFED = 4
TEXT_FONT_MONOSPACED = 8
TEXT_FONT_BOLD = 16
TEXT_OUTPUT_TEXT = 0
TEXT_OUTPUT_HTML = 1
TEXT_OUTPUT_JSON = 2
TEXT_OUTPUT_XML = 3
TEXT_OUTPUT_XHTML = 4
TEXT_PRESERVE_LIGATURES = mupdf.FZ_STEXT_PRESERVE_LIGATURES
TEXT_PRESERVE_WHITESPACE = mupdf.FZ_STEXT_PRESERVE_WHITESPACE
TEXT_PRESERVE_IMAGES = mupdf.FZ_STEXT_PRESERVE_IMAGES
TEXT_INHIBIT_SPACES = mupdf.FZ_STEXT_INHIBIT_SPACES
TEXT_DEHYPHENATE = mupdf.FZ_STEXT_DEHYPHENATE
TEXT_PRESERVE_SPANS = mupdf.FZ_STEXT_PRESERVE_SPANS
TEXT_MEDIABOX_CLIP = mupdf.FZ_STEXT_MEDIABOX_CLIP
TEXT_CID_FOR_UNKNOWN_UNICODE = mupdf.FZ_STEXT_USE_CID_FOR_UNKNOWN_UNICODE
if mupdf_version_tuple >= (1, 25):
TEXT_COLLECT_STRUCTURE = mupdf.FZ_STEXT_COLLECT_STRUCTURE
TEXT_ACCURATE_BBOXES = mupdf.FZ_STEXT_ACCURATE_BBOXES
TEXT_COLLECT_VECTORS = mupdf.FZ_STEXT_COLLECT_VECTORS
TEXT_IGNORE_ACTUALTEXT = mupdf.FZ_STEXT_IGNORE_ACTUALTEXT
TEXT_STEXT_SEGMENT = mupdf.FZ_STEXT_SEGMENT
else:
TEXT_COLLECT_STRUCTURE = 256
TEXT_ACCURATE_BBOXES = 512
TEXT_COLLECT_VECTORS = 1024
TEXT_IGNORE_ACTUALTEXT = 2048
TEXT_STEXT_SEGMENT = 4096
TEXTFLAGS_WORDS = (0
| TEXT_PRESERVE_LIGATURES
| TEXT_PRESERVE_WHITESPACE
| TEXT_MEDIABOX_CLIP
| TEXT_CID_FOR_UNKNOWN_UNICODE
)
TEXTFLAGS_BLOCKS = (0
| TEXT_PRESERVE_LIGATURES
| TEXT_PRESERVE_WHITESPACE
| TEXT_MEDIABOX_CLIP
| TEXT_CID_FOR_UNKNOWN_UNICODE
)
TEXTFLAGS_DICT = (0
| TEXT_PRESERVE_LIGATURES
| TEXT_PRESERVE_WHITESPACE
| TEXT_MEDIABOX_CLIP
| TEXT_PRESERVE_IMAGES
| TEXT_CID_FOR_UNKNOWN_UNICODE
)
TEXTFLAGS_RAWDICT = TEXTFLAGS_DICT
TEXTFLAGS_SEARCH = (0
| TEXT_PRESERVE_WHITESPACE
| TEXT_MEDIABOX_CLIP
| TEXT_DEHYPHENATE
| TEXT_CID_FOR_UNKNOWN_UNICODE
)
TEXTFLAGS_HTML = (0
| TEXT_PRESERVE_LIGATURES
| TEXT_PRESERVE_WHITESPACE
| TEXT_MEDIABOX_CLIP
| TEXT_PRESERVE_IMAGES
| TEXT_CID_FOR_UNKNOWN_UNICODE
)
TEXTFLAGS_XHTML = (0
| TEXT_PRESERVE_LIGATURES
| TEXT_PRESERVE_WHITESPACE
| TEXT_MEDIABOX_CLIP
| TEXT_PRESERVE_IMAGES
| TEXT_CID_FOR_UNKNOWN_UNICODE
)
TEXTFLAGS_XML = (0
| TEXT_PRESERVE_LIGATURES
| TEXT_PRESERVE_WHITESPACE
| TEXT_MEDIABOX_CLIP
| TEXT_CID_FOR_UNKNOWN_UNICODE
)
TEXTFLAGS_TEXT = (0
| TEXT_PRESERVE_LIGATURES
| TEXT_PRESERVE_WHITESPACE
| TEXT_MEDIABOX_CLIP
| TEXT_CID_FOR_UNKNOWN_UNICODE
)
# Simple text encoding options
TEXT_ENCODING_LATIN = 0
TEXT_ENCODING_GREEK = 1
TEXT_ENCODING_CYRILLIC = 2
TOOLS_JM_UNIQUE_ID = 0
# colorspace identifiers
CS_RGB = 1
CS_GRAY = 2
CS_CMYK = 3
# PDF Blend Modes
PDF_BM_Color = "Color"
PDF_BM_ColorBurn = "ColorBurn"
PDF_BM_ColorDodge = "ColorDodge"
PDF_BM_Darken = "Darken"
PDF_BM_Difference = "Difference"
PDF_BM_Exclusion = "Exclusion"
PDF_BM_HardLight = "HardLight"
PDF_BM_Hue = "Hue"
PDF_BM_Lighten = "Lighten"
PDF_BM_Luminosity = "Luminosity"
PDF_BM_Multiply = "Multiply"
PDF_BM_Normal = "Normal"
PDF_BM_Overlay = "Overlay"
PDF_BM_Saturation = "Saturation"
PDF_BM_Screen = "Screen"
PDF_BM_SoftLight = "Softlight"
# General text flags
TEXT_FONT_SUPERSCRIPT = 1
TEXT_FONT_ITALIC = 2
TEXT_FONT_SERIFED = 4
TEXT_FONT_MONOSPACED = 8
TEXT_FONT_BOLD = 16
annot_skel = {
"goto1": lambda a, b, c, d, e: f"<</A<</S/GoTo/D[{a} 0 R/XYZ {_format_g((b, c, d))}]>>/Rect[{e}]/BS<</W 0>>/Subtype/Link>>",
"goto2": lambda a, b: f"<</A<</S/GoTo/D{a}>>/Rect[{b}]/BS<</W 0>>/Subtype/Link>>",
"gotor1": lambda a, b, c, d, e, f, g: f"<</A<</S/GoToR/D[{a} /XYZ {_format_g((b, c, d))}]/F<</F({e})/UF({f})/Type/Filespec>>>>/Rect[{g}]/BS<</W 0>>/Subtype/Link>>",
"gotor2": lambda a, b, c: f"<</A<</S/GoToR/D{a}/F({b})>>/Rect[{c}]/BS<</W 0>>/Subtype/Link>>",
"launch": lambda a, b, c: f"<</A<</S/Launch/F<</F({a})/UF({b})/Type/Filespec>>>>/Rect[{c}]/BS<</W 0>>/Subtype/Link>>",
"uri": lambda a, b: f"<</A<</S/URI/URI({a})>>/Rect[{b}]/BS<</W 0>>/Subtype/Link>>",
"named": lambda a, b: f"<</A<</S/GoTo/D({a})/Type/Action>>/Rect[{b}]/BS<</W 0>>/Subtype/Link>>",
}
class FileDataError(RuntimeError):
"""Raised for documents with file structure issues."""
pass
class FileNotFoundError(RuntimeError):
"""Raised if file does not exist."""
pass
class EmptyFileError(FileDataError):
"""Raised when creating documents from zero-length data."""
pass
# propagate exception class to C-level code
#_set_FileDataError(FileDataError)
csRGB = Colorspace(CS_RGB)
csGRAY = Colorspace(CS_GRAY)
csCMYK = Colorspace(CS_CMYK)
# These don't appear to be visible in classic, but are used
# internally.
#
dictkey_align = "align"
dictkey_asc = "ascender"
dictkey_bbox = "bbox"
dictkey_blocks = "blocks"
dictkey_bpc = "bpc"
dictkey_c = "c"
dictkey_chars = "chars"
dictkey_color = "color"
dictkey_colorspace = "colorspace"
dictkey_content = "content"
dictkey_creationDate = "creationDate"
dictkey_cs_name = "cs-name"
dictkey_da = "da"
dictkey_dashes = "dashes"
dictkey_desc = "desc"
dictkey_desc = "descender"
dictkey_dir = "dir"
dictkey_effect = "effect"
dictkey_ext = "ext"
dictkey_filename = "filename"
dictkey_fill = "fill"
dictkey_flags = "flags"
dictkey_font = "font"
dictkey_glyph = "glyph"
dictkey_height = "height"
dictkey_id = "id"
dictkey_image = "image"
dictkey_items = "items"
dictkey_length = "length"
dictkey_lines = "lines"
dictkey_matrix = "transform"
dictkey_modDate = "modDate"
dictkey_name = "name"
dictkey_number = "number"
dictkey_origin = "origin"
dictkey_rect = "rect"
dictkey_size = "size"
dictkey_smask = "smask"
dictkey_spans = "spans"
dictkey_stroke = "stroke"
dictkey_style = "style"
dictkey_subject = "subject"
dictkey_text = "text"
dictkey_title = "title"
dictkey_type = "type"
dictkey_ufilename = "ufilename"
dictkey_width = "width"
dictkey_wmode = "wmode"
dictkey_xref = "xref"
dictkey_xres = "xres"
dictkey_yres = "yres"
try:
from pymupdf_fonts import fontdescriptors, fontbuffers
fitz_fontdescriptors = fontdescriptors.copy()
for k in fitz_fontdescriptors.keys():
fitz_fontdescriptors[k]["loader"] = fontbuffers[k]
del fontdescriptors, fontbuffers
except ImportError:
fitz_fontdescriptors = {}
symbol_glyphs = ( # Glyph list for the built-in font 'Symbol'
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(32, 0.25),
(33, 0.333),
(34, 0.713),
(35, 0.5),
(36, 0.549),
(37, 0.833),
(38, 0.778),
(39, 0.439),
(40, 0.333),
(41, 0.333),
(42, 0.5),
(43, 0.549),
(44, 0.25),
(45, 0.549),
(46, 0.25),
(47, 0.278),
(48, 0.5),
(49, 0.5),
(50, 0.5),
(51, 0.5),
(52, 0.5),
(53, 0.5),
(54, 0.5),
(55, 0.5),
(56, 0.5),
(57, 0.5),
(58, 0.278),
(59, 0.278),
(60, 0.549),
(61, 0.549),
(62, 0.549),
(63, 0.444),
(64, 0.549),
(65, 0.722),
(66, 0.667),
(67, 0.722),
(68, 0.612),
(69, 0.611),
(70, 0.763),
(71, 0.603),
(72, 0.722),
(73, 0.333),
(74, 0.631),
(75, 0.722),
(76, 0.686),
(77, 0.889),
(78, 0.722),
(79, 0.722),
(80, 0.768),
(81, 0.741),
(82, 0.556),
(83, 0.592),
(84, 0.611),
(85, 0.69),
(86, 0.439),
(87, 0.768),
(88, 0.645),
(89, 0.795),
(90, 0.611),
(91, 0.333),
(92, 0.863),
(93, 0.333),
(94, 0.658),
(95, 0.5),
(96, 0.5),
(97, 0.631),
(98, 0.549),
(99, 0.549),
(100, 0.494),
(101, 0.439),
(102, 0.521),
(103, 0.411),
(104, 0.603),
(105, 0.329),
(106, 0.603),
(107, 0.549),
(108, 0.549),
(109, 0.576),
(110, 0.521),
(111, 0.549),
(112, 0.549),
(113, 0.521),
(114, 0.549),
(115, 0.603),
(116, 0.439),
(117, 0.576),
(118, 0.713),
(119, 0.686),
(120, 0.493),
(121, 0.686),
(122, 0.494),
(123, 0.48),
(124, 0.2),
(125, 0.48),
(126, 0.549),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(183, 0.46),
(160, 0.25),
(161, 0.62),
(162, 0.247),
(163, 0.549),
(164, 0.167),
(165, 0.713),
(166, 0.5),
(167, 0.753),
(168, 0.753),
(169, 0.753),
(170, 0.753),
(171, 1.042),
(172, 0.713),
(173, 0.603),
(174, 0.987),
(175, 0.603),
(176, 0.4),
(177, 0.549),
(178, 0.411),
(179, 0.549),
(180, 0.549),
(181, 0.576),
(182, 0.494),
(183, 0.46),
(184, 0.549),
(185, 0.549),
(186, 0.549),
(187, 0.549),
(188, 1),
(189, 0.603),
(190, 1),
(191, 0.658),
(192, 0.823),
(193, 0.686),
(194, 0.795),
(195, 0.987),
(196, 0.768),
(197, 0.768),
(198, 0.823),
(199, 0.768),
(200, 0.768),
(201, 0.713),
(202, 0.713),
(203, 0.713),
(204, 0.713),
(205, 0.713),
(206, 0.713),
(207, 0.713),
(208, 0.768),
(209, 0.713),
(210, 0.79),
(211, 0.79),
(212, 0.89),
(213, 0.823),
(214, 0.549),
(215, 0.549),
(216, 0.713),
(217, 0.603),
(218, 0.603),
(219, 1.042),
(220, 0.987),
(221, 0.603),
(222, 0.987),
(223, 0.603),
(224, 0.494),
(225, 0.329),
(226, 0.79),
(227, 0.79),
(228, 0.786),
(229, 0.713),
(230, 0.384),
(231, 0.384),
(232, 0.384),
(233, 0.384),
(234, 0.384),
(235, 0.384),
(236, 0.494),
(237, 0.494),
(238, 0.494),
(239, 0.494),
(183, 0.46),
(241, 0.329),
(242, 0.274),
(243, 0.686),
(244, 0.686),
(245, 0.686),
(246, 0.384),
(247, 0.549),
(248, 0.384),
(249, 0.384),
(250, 0.384),
(251, 0.384),
(252, 0.494),
(253, 0.494),
(254, 0.494),
(183, 0.46),
)
zapf_glyphs = ( # Glyph list for the built-in font 'ZapfDingbats'
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(32, 0.278),
(33, 0.974),
(34, 0.961),
(35, 0.974),
(36, 0.98),
(37, 0.719),
(38, 0.789),
(39, 0.79),
(40, 0.791),
(41, 0.69),
(42, 0.96),
(43, 0.939),
(44, 0.549),
(45, 0.855),
(46, 0.911),
(47, 0.933),
(48, 0.911),
(49, 0.945),
(50, 0.974),
(51, 0.755),
(52, 0.846),
(53, 0.762),
(54, 0.761),
(55, 0.571),
(56, 0.677),
(57, 0.763),
(58, 0.76),
(59, 0.759),
(60, 0.754),
(61, 0.494),
(62, 0.552),
(63, 0.537),
(64, 0.577),
(65, 0.692),
(66, 0.786),
(67, 0.788),
(68, 0.788),
(69, 0.79),
(70, 0.793),
(71, 0.794),
(72, 0.816),
(73, 0.823),
(74, 0.789),
(75, 0.841),
(76, 0.823),
(77, 0.833),
(78, 0.816),
(79, 0.831),
(80, 0.923),
(81, 0.744),
(82, 0.723),
(83, 0.749),
(84, 0.79),
(85, 0.792),
(86, 0.695),
(87, 0.776),
(88, 0.768),
(89, 0.792),
(90, 0.759),
(91, 0.707),
(92, 0.708),
(93, 0.682),
(94, 0.701),
(95, 0.826),
(96, 0.815),
(97, 0.789),
(98, 0.789),
(99, 0.707),
(100, 0.687),
(101, 0.696),
(102, 0.689),
(103, 0.786),
(104, 0.787),
(105, 0.713),
(106, 0.791),
(107, 0.785),
(108, 0.791),
(109, 0.873),
(110, 0.761),
(111, 0.762),
(112, 0.762),
(113, 0.759),
(114, 0.759),
(115, 0.892),
(116, 0.892),
(117, 0.788),
(118, 0.784),
(119, 0.438),
(120, 0.138),
(121, 0.277),
(122, 0.415),
(123, 0.392),
(124, 0.392),
(125, 0.668),
(126, 0.668),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(183, 0.788),
(161, 0.732),
(162, 0.544),
(163, 0.544),
(164, 0.91),
(165, 0.667),
(166, 0.76),
(167, 0.76),
(168, 0.776),
(169, 0.595),
(170, 0.694),
(171, 0.626),
(172, 0.788),
(173, 0.788),
(174, 0.788),
(175, 0.788),
(176, 0.788),
(177, 0.788),
(178, 0.788),
(179, 0.788),
(180, 0.788),
(181, 0.788),
(182, 0.788),
(183, 0.788),
(184, 0.788),
(185, 0.788),
(186, 0.788),
(187, 0.788),
(188, 0.788),
(189, 0.788),
(190, 0.788),
(191, 0.788),
(192, 0.788),
(193, 0.788),
(194, 0.788),
(195, 0.788),
(196, 0.788),
(197, 0.788),
(198, 0.788),
(199, 0.788),
(200, 0.788),
(201, 0.788),
(202, 0.788),
(203, 0.788),
(204, 0.788),
(205, 0.788),
(206, 0.788),
(207, 0.788),
(208, 0.788),
(209, 0.788),
(210, 0.788),
(211, 0.788),
(212, 0.894),
(213, 0.838),
(214, 1.016),
(215, 0.458),
(216, 0.748),
(217, 0.924),
(218, 0.748),
(219, 0.918),
(220, 0.927),
(221, 0.928),
(222, 0.928),
(223, 0.834),
(224, 0.873),
(225, 0.828),
(226, 0.924),
(227, 0.924),
(228, 0.917),
(229, 0.93),
(230, 0.931),
(231, 0.463),
(232, 0.883),
(233, 0.836),
(234, 0.836),
(235, 0.867),
(236, 0.867),
(237, 0.696),
(238, 0.696),
(239, 0.874),
(183, 0.788),
(241, 0.874),
(242, 0.76),
(243, 0.946),
(244, 0.771),
(245, 0.865),
(246, 0.771),
(247, 0.888),
(248, 0.967),
(249, 0.888),
(250, 0.831),
(251, 0.873),
(252, 0.927),
(253, 0.97),
(183, 0.788),
(183, 0.788),
)
# Functions
#
def _read_samples( pixmap, offset, n):
# fixme: need to be able to get a sample in one call, as a Python
# bytes or similar.
ret = []
if not pixmap.samples():
# mupdf.fz_samples_get() gives a segv if pixmap->samples is null.
return ret
for i in range( n):
ret.append( mupdf.fz_samples_get( pixmap, offset + i))
return bytes( ret)
def _INRANGE(v, low, high):
return low <= v and v <= high
def _remove_dest_range(pdf, numbers):
pagecount = mupdf.pdf_count_pages(pdf)
for i in range(pagecount):
n1 = i
if n1 in numbers:
continue
pageref = mupdf.pdf_lookup_page_obj( pdf, i)
annots = mupdf.pdf_dict_get( pageref, PDF_NAME('Annots'))
if not annots.m_internal:
continue
len_ = mupdf.pdf_array_len(annots)
for j in range(len_ - 1, -1, -1):
o = mupdf.pdf_array_get( annots, j)
if not mupdf.pdf_name_eq( mupdf.pdf_dict_get( o, PDF_NAME('Subtype')), PDF_NAME('Link')):
continue
action = mupdf.pdf_dict_get( o, PDF_NAME('A'))
dest = mupdf.pdf_dict_get( o, PDF_NAME('Dest'))
if action.m_internal:
if not mupdf.pdf_name_eq( mupdf.pdf_dict_get( action, PDF_NAME('S')), PDF_NAME('GoTo')):
continue
dest = mupdf.pdf_dict_get( action, PDF_NAME('D'))
pno = -1
if mupdf.pdf_is_array( dest):
target = mupdf.pdf_array_get( dest, 0)
pno = mupdf.pdf_lookup_page_number( pdf, target)
elif mupdf.pdf_is_string( dest):
location, _, _ = mupdf.fz_resolve_link( pdf.super(), mupdf.pdf_to_text_string( dest))
pno = location.page
if pno < 0: # page number lookup did not work
continue
n1 = pno
if n1 in numbers:
mupdf.pdf_array_delete( annots, j)
def ASSERT_PDF(cond):
assert isinstance(cond, (mupdf.PdfPage, mupdf.PdfDocument)), f'{type(cond)=} {cond=}'
if not cond.m_internal:
raise Exception(MSG_IS_NO_PDF)
def EMPTY_IRECT():
return IRect(FZ_MAX_INF_RECT, FZ_MAX_INF_RECT, FZ_MIN_INF_RECT, FZ_MIN_INF_RECT)
def EMPTY_QUAD():
return EMPTY_RECT().quad
def EMPTY_RECT():
return Rect(FZ_MAX_INF_RECT, FZ_MAX_INF_RECT, FZ_MIN_INF_RECT, FZ_MIN_INF_RECT)
def ENSURE_OPERATION(pdf):
if not JM_have_operation(pdf):
raise Exception("No journalling operation started")
def INFINITE_IRECT():
return IRect(FZ_MIN_INF_RECT, FZ_MIN_INF_RECT, FZ_MAX_INF_RECT, FZ_MAX_INF_RECT)
def INFINITE_QUAD():
return INFINITE_RECT().quad
def INFINITE_RECT():
return Rect(FZ_MIN_INF_RECT, FZ_MIN_INF_RECT, FZ_MAX_INF_RECT, FZ_MAX_INF_RECT)
def JM_BinFromBuffer(buffer_):
'''
Turn fz_buffer into a Python bytes object
'''
assert isinstance(buffer_, mupdf.FzBuffer)
ret = mupdf.fz_buffer_extract_copy(buffer_)
return ret
def JM_EscapeStrFromStr(c):
# `c` is typically from SWIG which will have converted a `const char*` from
# C into a Python `str` using `PyUnicode_DecodeUTF8(carray, static_cast<
# Py_ssize_t >(size), "surrogateescape")`. This gives us a Python `str`
# with some characters encoded as a \0xdcXY sequence, where `XY` are hex
# digits for an invalid byte in the original `const char*`.
#
# This is actually a reasonable way of representing arbitrary
# strings from C, but we want to mimic what PyMuPDF does. It uses
# `PyUnicode_DecodeRawUnicodeEscape(c, (Py_ssize_t) strlen(c), "replace")`
# which gives a string containing actual unicode characters for any invalid
# bytes.
#
# We mimic this by converting the `str` to a `bytes` with 'surrogateescape'
# to recognise \0xdcXY sequences, then convert the individual bytes into a
# `str` using `chr()`.
#
# Would be good to have a more efficient way to do this.
#
if c is None:
return ''
assert isinstance(c, str), f'{type(c)=}'
b = c.encode('utf8', 'surrogateescape')
ret = ''
for bb in b:
ret += chr(bb)
return ret
def JM_BufferFromBytes(stream):
'''
Make fz_buffer from a PyBytes, PyByteArray or io.BytesIO object. If a text
io.BytesIO, we convert to binary by encoding as utf8.
'''
if isinstance(stream, (bytes, bytearray)):
data = stream
elif hasattr(stream, 'getvalue'):
data = stream.getvalue()
if isinstance(data, str):
data = data.encode('utf-8')
if not isinstance(data, (bytes, bytearray)):
raise Exception(f'.getvalue() returned unexpected type: {type(data)}')
else:
return mupdf.FzBuffer()
return mupdf.fz_new_buffer_from_copied_data(data)
def JM_FLOAT_ITEM(obj, idx):
if not PySequence_Check(obj):
return None
return float(obj[idx])
def JM_INT_ITEM(obj, idx):
if idx < len(obj):
temp = obj[idx]
if isinstance(temp, (int, float)):
return 0, temp
return 1, None
def JM_pixmap_from_page(doc, page, ctm, cs, alpha, annots, clip):
'''
Pixmap creation directly using a short-lived displaylist, so we can support
separations.
'''
SPOTS_NONE = 0
SPOTS_OVERPRINT_SIM = 1
SPOTS_FULL = 2
FZ_ENABLE_SPOT_RENDERING = True # fixme: this is a build-time setting in MuPDF's config.h.
if FZ_ENABLE_SPOT_RENDERING:
spots = SPOTS_OVERPRINT_SIM
else:
spots = SPOTS_NONE
seps = None
colorspace = cs
matrix = JM_matrix_from_py(ctm)
rect = mupdf.fz_bound_page(page)
rclip = JM_rect_from_py(clip)
rect = mupdf.fz_intersect_rect(rect, rclip) # no-op if clip is not given
rect = mupdf.fz_transform_rect(rect, matrix)
bbox = mupdf.fz_round_rect(rect)
# Pixmap of the document's /OutputIntents ("output intents")
oi = mupdf.fz_document_output_intent(doc)
# if present and compatible, use it instead of the parameter
if oi.m_internal:
if mupdf.fz_colorspace_n(oi) == mupdf.fz_colorspace_n(cs):
colorspace = mupdf.fz_keep_colorspace(oi)
# check if spots rendering is available and if so use separations
if spots != SPOTS_NONE:
seps = mupdf.fz_page_separations(page)
if seps.m_internal:
n = mupdf.fz_count_separations(seps)
if spots == SPOTS_FULL:
for i in range(n):
mupdf.fz_set_separation_behavior(seps, i, mupdf.FZ_SEPARATION_SPOT)
else:
for i in range(n):
mupdf.fz_set_separation_behavior(seps, i, mupdf.FZ_SEPARATION_COMPOSITE)
elif mupdf.fz_page_uses_overprint(page):
# This page uses overprint, so we need an empty
# sep object to force the overprint simulation on.
seps = mupdf.fz_new_separations(0)
elif oi.m_internal and mupdf.fz_colorspace_n(oi) != mupdf.fz_colorspace_n(colorspace):
# We have an output intent, and it's incompatible
# with the colorspace our device needs. Force the
# overprint simulation on, because this ensures that
# we 'simulate' the output intent too.
seps = mupdf.fz_new_separations(0)
pix = mupdf.fz_new_pixmap_with_bbox(colorspace, bbox, seps, alpha)
if alpha:
mupdf.fz_clear_pixmap(pix)
else:
mupdf.fz_clear_pixmap_with_value(pix, 0xFF)
dev = mupdf.fz_new_draw_device(matrix, pix)
if annots:
mupdf.fz_run_page(page, dev, mupdf.FzMatrix(), mupdf.FzCookie())
else:
mupdf.fz_run_page_contents(page, dev, mupdf.FzMatrix(), mupdf.FzCookie())
mupdf.fz_close_device(dev)
return pix
def JM_StrAsChar(x):
# fixme: should encode, but swig doesn't pass bytes to C as const char*.
return x
#return x.encode('utf8')
def JM_TUPLE(o: typing.Sequence) -> tuple:
return tuple(map(lambda x: round(x, 5) if abs(x) >= 1e-4 else 0, o))
def JM_TUPLE3(o: typing.Sequence) -> tuple:
return tuple(map(lambda x: round(x, 3) if abs(x) >= 1e-3 else 0, o))
def JM_UnicodeFromStr(s):
if s is None:
return ''
if isinstance(s, bytes):
s = s.decode('utf8')
assert isinstance(s, str), f'{type(s)=} {s=}'
return s
def JM_add_annot_id(annot, stem):
'''
Add a unique /NM key to an annotation or widget.
Append a number to 'stem' such that the result is a unique name.
'''
assert isinstance(annot, mupdf.PdfAnnot)
page = mupdf.pdf_annot_page( annot)
annot_obj = mupdf.pdf_annot_obj( annot)
names = JM_get_annot_id_list(page)
i = 0
while 1:
stem_id = f'{JM_annot_id_stem}-{stem}{i}'
if stem_id not in names:
break
i += 1
response = JM_StrAsChar(stem_id)
name = mupdf.pdf_new_string( response, len(response))
mupdf.pdf_dict_puts(annot_obj, "NM", name)
page.doc().m_internal.resynth_required = 0
def JM_add_oc_object(pdf, ref, xref):
'''
Add OC object reference to a dictionary
'''
indobj = mupdf.pdf_new_indirect(pdf, xref, 0)
if not mupdf.pdf_is_dict(indobj):
RAISEPY(MSG_BAD_OC_REF, PyExc_ValueError)
type_ = mupdf.pdf_dict_get(indobj, PDF_NAME('Type'))
if (mupdf.pdf_objcmp(type_, PDF_NAME('OCG')) == 0
or mupdf.pdf_objcmp(type_, PDF_NAME('OCMD')) == 0
):
mupdf.pdf_dict_put(ref, PDF_NAME('OC'), indobj)
else:
RAISEPY(MSG_BAD_OC_REF, PyExc_ValueError)
def JM_annot_border(annot_obj):
dash_py = list()
style = None
width = -1
clouds = -1
obj = None
obj = mupdf.pdf_dict_get( annot_obj, PDF_NAME('Border'))
if mupdf.pdf_is_array( obj):
width = mupdf.pdf_to_real( mupdf.pdf_array_get( obj, 2))
if mupdf.pdf_array_len( obj) == 4:
dash = mupdf.pdf_array_get( obj, 3)
for i in range( mupdf.pdf_array_len( dash)):
val = mupdf.pdf_to_int( mupdf.pdf_array_get( dash, i))
dash_py.append( val)
bs_o = mupdf.pdf_dict_get( annot_obj, PDF_NAME('BS'))
if bs_o.m_internal:
width = mupdf.pdf_to_real( mupdf.pdf_dict_get( bs_o, PDF_NAME('W')))
style = mupdf.pdf_to_name( mupdf.pdf_dict_get( bs_o, PDF_NAME('S')))
if style == '':
style = None
obj = mupdf.pdf_dict_get( bs_o, PDF_NAME('D'))
if obj.m_internal:
for i in range( mupdf.pdf_array_len( obj)):
val = mupdf.pdf_to_int( mupdf.pdf_array_get( obj, i))
dash_py.append( val)
obj = mupdf.pdf_dict_get( annot_obj, PDF_NAME('BE'))
if obj.m_internal:
clouds = mupdf.pdf_to_int( mupdf.pdf_dict_get( obj, PDF_NAME('I')))
res = dict()
res[ dictkey_width] = width
res[ dictkey_dashes] = tuple( dash_py)
res[ dictkey_style] = style
res[ 'clouds'] = clouds
return res
def JM_annot_colors(annot_obj):
res = dict()
bc = list() # stroke colors
fc =list() # fill colors
o = mupdf.pdf_dict_get(annot_obj, mupdf.PDF_ENUM_NAME_C)
if mupdf.pdf_is_array(o):
n = mupdf.pdf_array_len(o)
for i in range(n):
col = mupdf.pdf_to_real( mupdf.pdf_array_get(o, i))
bc.append(col)
res[dictkey_stroke] = bc
o = mupdf.pdf_dict_gets(annot_obj, "IC")
if mupdf.pdf_is_array(o):
n = mupdf.pdf_array_len(o)
for i in range(n):
col = mupdf.pdf_to_real( mupdf.pdf_array_get(o, i))
fc.append(col)
res[dictkey_fill] = fc
return res
def JM_annot_set_border( border, doc, annot_obj):
assert isinstance(border, dict)
obj = None
dashlen = 0
nwidth = border.get( dictkey_width) # new width
ndashes = border.get( dictkey_dashes) # new dashes
nstyle = border.get( dictkey_style) # new style
nclouds = border.get( 'clouds', -1) # new clouds value
# get old border properties
oborder = JM_annot_border( annot_obj)
# delete border-related entries
mupdf.pdf_dict_del( annot_obj, PDF_NAME('BS'))
mupdf.pdf_dict_del( annot_obj, PDF_NAME('BE'))
mupdf.pdf_dict_del( annot_obj, PDF_NAME('Border'))
# populate border items: keep old values for any omitted new ones
if nwidth < 0:
nwidth = oborder.get( dictkey_width) # no new width: keep current
if ndashes is None:
ndashes = oborder.get( dictkey_dashes) # no new dashes: keep old
if nstyle is None:
nstyle = oborder.get( dictkey_style) # no new style: keep old
if nclouds < 0:
nclouds = oborder.get( "clouds", -1) # no new clouds: keep old
if isinstance( ndashes, tuple) and len( ndashes) > 0:
dashlen = len( ndashes)
darr = mupdf.pdf_new_array( doc, dashlen)
for d in ndashes:
mupdf.pdf_array_push_int( darr, d)
mupdf.pdf_dict_putl( annot_obj, darr, PDF_NAME('BS'), PDF_NAME('D'))
mupdf.pdf_dict_putl(
annot_obj,
mupdf.pdf_new_real( nwidth),
PDF_NAME('BS'),
PDF_NAME('W'),
)
if dashlen == 0:
obj = JM_get_border_style( nstyle)
else:
obj = PDF_NAME('D')
mupdf.pdf_dict_putl( annot_obj, obj, PDF_NAME('BS'), PDF_NAME('S'))
if nclouds > 0:
mupdf.pdf_dict_put_dict( annot_obj, PDF_NAME('BE'), 2)
obj = mupdf.pdf_dict_get( annot_obj, PDF_NAME('BE'))
mupdf.pdf_dict_put( obj, PDF_NAME('S'), PDF_NAME('C'))
mupdf.pdf_dict_put_int( obj, PDF_NAME('I'), nclouds)
def make_escape(ch):
if ch == 92:
return "\\u005c"
elif 32 <= ch <= 127 or ch == 10:
return chr(ch)
elif 0xd800 <= ch <= 0xdfff: # orphaned surrogate
return "\\ufffd"
elif ch <= 0xffff:
return "\\u%04x" % ch
else:
return "\\U%08x" % ch
def JM_append_rune(buff, ch):
"""
APPEND non-ascii runes in unicode escape format to fz_buffer.
"""
mupdf.fz_append_string(buff, make_escape(ch))
def JM_append_word(lines, buff, wbbox, block_n, line_n, word_n):
'''
Functions for wordlist output
'''
s = JM_EscapeStrFromBuffer(buff)
litem = (
wbbox.x0,
wbbox.y0,
wbbox.x1,
wbbox.y1,
s,
block_n,
line_n,
word_n,
)
lines.append(litem)
return word_n + 1, mupdf.FzRect(mupdf.FzRect.Fixed_EMPTY) # word counter
def JM_add_layer_config( pdf, name, creator, ON):
'''
Add OC configuration to the PDF catalog
'''
ocp = JM_ensure_ocproperties( pdf)
configs = mupdf.pdf_dict_get( ocp, PDF_NAME('Configs'))
if not mupdf.pdf_is_array( configs):
configs = mupdf.pdf_dict_put_array( ocp, PDF_NAME('Configs'), 1)
D = mupdf.pdf_new_dict( pdf, 5)
mupdf.pdf_dict_put_text_string( D, PDF_NAME('Name'), name)
if creator is not None:
mupdf.pdf_dict_put_text_string( D, PDF_NAME('Creator'), creator)
mupdf.pdf_dict_put( D, PDF_NAME('BaseState'), PDF_NAME('OFF'))
onarray = mupdf.pdf_dict_put_array( D, PDF_NAME('ON'), 5)
if not ON:
pass
else:
ocgs = mupdf.pdf_dict_get( ocp, PDF_NAME('OCGs'))
n = len(ON)
for i in range(n):
xref = 0
e, xref = JM_INT_ITEM(ON, i)
if e == 1:
continue
ind = mupdf.pdf_new_indirect( pdf, xref, 0)
if mupdf.pdf_array_contains( ocgs, ind):
mupdf.pdf_array_push( onarray, ind)
mupdf.pdf_array_push( configs, D)
def JM_char_bbox(line, ch):
'''
return rect of char quad
'''
q = JM_char_quad(line, ch)
r = mupdf.fz_rect_from_quad(q)
if not line.m_internal.wmode:
return r
if r.y1 < r.y0 + ch.m_internal.size:
r.y0 = r.y1 - ch.m_internal.size
return r
def JM_char_font_flags(font, line, ch):
flags = detect_super_script(line, ch)
flags += mupdf.fz_font_is_italic(font) * TEXT_FONT_ITALIC
flags += mupdf.fz_font_is_serif(font) * TEXT_FONT_SERIFED
flags += mupdf.fz_font_is_monospaced(font) * TEXT_FONT_MONOSPACED
flags += mupdf.fz_font_is_bold(font) * TEXT_FONT_BOLD
return flags
def JM_char_quad(line, ch):
'''
re-compute char quad if ascender/descender values make no sense
'''
if 1 and g_use_extra:
# This reduces time taken to extract text from PyMuPDF.pdf from 20s to
# 15s.
return mupdf.FzQuad(extra.JM_char_quad( line.m_internal, ch.m_internal))
assert isinstance(line, mupdf.FzStextLine)
assert isinstance(ch, mupdf.FzStextChar)
if _globals.skip_quad_corrections: # no special handling
return ch.quad
if line.m_internal.wmode: # never touch vertical write mode
return ch.quad
font = mupdf.FzFont(mupdf.ll_fz_keep_font(ch.m_internal.font))
asc = JM_font_ascender(font)
dsc = JM_font_descender(font)
fsize = ch.m_internal.size
asc_dsc = asc - dsc + FLT_EPSILON
if asc_dsc >= 1 and _globals.small_glyph_heights == 0: # no problem
return mupdf.FzQuad(ch.m_internal.quad)
# Re-compute quad with adjusted ascender / descender values:
# Move ch->origin to (0,0) and de-rotate quad, then adjust the corners,
# re-rotate and move back to ch->origin location.
fsize = ch.m_internal.size
bbox = mupdf.fz_font_bbox(font)
fwidth = bbox.x1 - bbox.x0
if asc < 1e-3: # probably Tesseract glyphless font
dsc = -0.1
asc = 0.9
asc_dsc = 1.0
if _globals.small_glyph_heights or asc_dsc < 1:
dsc = dsc / asc_dsc
asc = asc / asc_dsc
asc_dsc = asc - dsc
asc = asc * fsize / asc_dsc
dsc = dsc * fsize / asc_dsc
# Re-compute quad with the adjusted ascender / descender values:
# Move ch->origin to (0,0) and de-rotate quad, then adjust the corners,
# re-rotate and move back to ch->origin location.
c = line.m_internal.dir.x # cosine
s = line.m_internal.dir.y # sine
trm1 = mupdf.fz_make_matrix(c, -s, s, c, 0, 0) # derotate
trm2 = mupdf.fz_make_matrix(c, s, -s, c, 0, 0) # rotate
if (c == -1): # left-right flip
trm1.d = 1
trm2.d = 1
xlate1 = mupdf.fz_make_matrix(1, 0, 0, 1, -ch.m_internal.origin.x, -ch.m_internal.origin.y)
xlate2 = mupdf.fz_make_matrix(1, 0, 0, 1, ch.m_internal.origin.x, ch.m_internal.origin.y)
quad = mupdf.fz_transform_quad(mupdf.FzQuad(ch.m_internal.quad), xlate1) # move origin to (0,0)
quad = mupdf.fz_transform_quad(quad, trm1) # de-rotate corners
# adjust vertical coordinates
if c == 1 and quad.ul.y > 0: # up-down flip
quad.ul.y = asc
quad.ur.y = asc
quad.ll.y = dsc
quad.lr.y = dsc
else:
quad.ul.y = -asc
quad.ur.y = -asc
quad.ll.y = -dsc
quad.lr.y = -dsc
# adjust horizontal coordinates that are too crazy:
# (1) left x must be >= 0
# (2) if bbox width is 0, lookup char advance in font.
if quad.ll.x < 0:
quad.ll.x = 0
quad.ul.x = 0
cwidth = quad.lr.x - quad.ll.x
if cwidth < FLT_EPSILON:
glyph = mupdf.fz_encode_character( font, ch.m_internal.c)
if glyph:
fwidth = mupdf.fz_advance_glyph( font, glyph, line.m_internal.wmode)
quad.lr.x = quad.ll.x + fwidth * fsize
quad.ur.x = quad.lr.x
quad = mupdf.fz_transform_quad(quad, trm2) # rotate back
quad = mupdf.fz_transform_quad(quad, xlate2) # translate back
return quad
def JM_choice_options(annot):
'''
return list of choices for list or combo boxes
'''
annot_obj = mupdf.pdf_annot_obj( annot.this)
if mupdf_version_tuple >= (1, 24):
opts = mupdf.pdf_choice_widget_options2( annot, 0)
else:
# pdf_choice_widget_options() is not usable from python, so we
# implement it ourselves here.
#
def pdf_choice_widget_options( annot, exportval):
#log( '{=type(annot)}')
optarr = mupdf.pdf_dict_get_inheritable( mupdf.pdf_annot_obj(annot.this), PDF_NAME('Opt'))
#log( '{optarr=}')
n = mupdf.pdf_array_len(optarr)
opts = []
if not n:
return opts
optarr = mupdf.pdf_dict_get(annot_obj, PDF_NAME('Opt'))
for i in range(n):
m = mupdf.pdf_array_len(mupdf.pdf_array_get(optarr, i))
if m == 2:
val = (
mupdf.pdf_to_text_string(mupdf.pdf_array_get(mupdf.pdf_array_get(optarr, i), 0)),
mupdf.pdf_to_text_string(mupdf.pdf_array_get(mupdf.pdf_array_get(optarr, i), 1)),
)
opts.append(val)
else:
val = JM_UnicodeFromStr(mupdf.pdf_to_text_string(mupdf.pdf_array_get(optarr, i)))
opts.append(val)
return opts
opts = pdf_choice_widget_options( annot, 0)
n = len( opts)
if n == 0:
return # wrong widget type
optarr = mupdf.pdf_dict_get( annot_obj, PDF_NAME('Opt'))
liste = []
for i in range( n):
m = mupdf.pdf_array_len( mupdf.pdf_array_get( optarr, i))
if m == 2:
val = (
mupdf.pdf_to_text_string( mupdf.pdf_array_get( mupdf.pdf_array_get( optarr, i), 0)),
mupdf.pdf_to_text_string( mupdf.pdf_array_get( mupdf.pdf_array_get( optarr, i), 1)),
)
liste.append( val)
else:
val = mupdf.pdf_to_text_string( mupdf.pdf_array_get( optarr, i))
liste.append( val)
return liste
def JM_clear_pixmap_rect_with_value(dest, value, b):
'''
Clear a pixmap rectangle - my version also supports non-alpha pixmaps
'''
b = mupdf.fz_intersect_irect(b, mupdf.fz_pixmap_bbox(dest))
w = b.x1 - b.x0
y = b.y1 - b.y0
if w <= 0 or y <= 0:
return 0
destspan = dest.stride()
destp = destspan * (b.y0 - dest.y()) + dest.n() * (b.x0 - dest.x())
# CMYK needs special handling (and potentially any other subtractive colorspaces)
if mupdf.fz_colorspace_n(dest.colorspace()) == 4:
value = 255 - value
while 1:
s = destp
for x in range(0, w):
mupdf.fz_samples_set(dest, s, 0)
s += 1
mupdf.fz_samples_set(dest, s, 0)
s += 1
mupdf.fz_samples_set(dest, s, 0)
s += 1
mupdf.fz_samples_set(dest, s, value)
s += 1
if dest.alpha():
mupdf.fz_samples_set(dest, s, 255)
s += 1
destp += destspan
if y == 0:
break
y -= 1
return 1
while 1:
s = destp
for x in range(w):
for k in range(dest.n()-1):
mupdf.fz_samples_set(dest, s, value)
s += 1
if dest.alpha():
mupdf.fz_samples_set(dest, s, 255)
s += 1
else:
mupdf.fz_samples_set(dest, s, value)
s += 1
destp += destspan
if y == 0:
break
y -= 1
return 1
def JM_color_FromSequence(color):
if isinstance(color, (int, float)): # maybe just a single float
color = color[0]
if not isinstance( color, (list, tuple)):
return -1, []
if len(color) not in (0, 1, 3, 4):
return -1, []
ret = color[:]
for i in range(len(ret)):
if ret[i] < 0 or ret[i] > 1:
ret[i] = 1
return len(ret), ret
def JM_color_count( pm, clip):
rc = dict()
cnt = 0
irect = mupdf.fz_pixmap_bbox( pm)
irect = mupdf.fz_intersect_irect(irect, mupdf.fz_round_rect(JM_rect_from_py(clip)))
stride = pm.stride()
width = irect.x1 - irect.x0
height = irect.y1 - irect.y0
n = pm.n()
substride = width * n
s = stride * (irect.y0 - pm.y()) + (irect.x0 - pm.x()) * n
oldpix = _read_samples( pm, s, n)
cnt = 0
if mupdf.fz_is_empty_irect(irect):
return rc
for i in range( height):
for j in range( 0, substride, n):
newpix = _read_samples( pm, s + j, n)
if newpix != oldpix:
pixel = oldpix
c = rc.get( pixel, None)
if c is not None:
cnt += c
rc[ pixel] = cnt
cnt = 1
oldpix = newpix
else:
cnt += 1
s += stride
pixel = oldpix
c = rc.get( pixel)
if c is not None:
cnt += c
rc[ pixel] = cnt
return rc
def JM_compress_buffer(inbuffer):
'''
compress char* into a new buffer
'''
data, compressed_length = mupdf.fz_new_deflated_data_from_buffer(
inbuffer,
mupdf.FZ_DEFLATE_BEST,
)
#log( '{=data compressed_length}')
if not data or compressed_length == 0:
return None
buf = mupdf.FzBuffer(mupdf.fz_new_buffer_from_data(data, compressed_length))
mupdf.fz_resize_buffer(buf, compressed_length)
return buf
def JM_copy_rectangle(page, area):
need_new_line = 0
buffer = io.StringIO()
for block in page:
if block.m_internal.type != mupdf.FZ_STEXT_BLOCK_TEXT:
continue
for line in block:
line_had_text = 0
for ch in line:
r = JM_char_bbox(line, ch)
if JM_rects_overlap(area, r):
line_had_text = 1
if need_new_line:
buffer.write("\n")
need_new_line = 0
buffer.write(make_escape(ch.m_internal.c))
if line_had_text:
need_new_line = 1
s = buffer.getvalue() # take over the data
return s
def JM_convert_to_pdf(doc, fp, tp, rotate):
'''
Convert any MuPDF document to a PDF
Returns bytes object containing the PDF, created via 'write' function.
'''
pdfout = mupdf.PdfDocument()
incr = 1
s = fp
e = tp
if fp > tp:
incr = -1 # count backwards
s = tp # adjust ...
e = fp # ... range
rot = JM_norm_rotation(rotate)
i = fp
while 1: # interpret & write document pages as PDF pages
if not _INRANGE(i, s, e):
break
page = mupdf.fz_load_page(doc, i)
mediabox = mupdf.fz_bound_page(page)
dev, resources, contents = mupdf.pdf_page_write(pdfout, mediabox)
mupdf.fz_run_page(page, dev, mupdf.FzMatrix(), mupdf.FzCookie())
mupdf.fz_close_device(dev)
dev = None
page_obj = mupdf.pdf_add_page(pdfout, mediabox, rot, resources, contents)
mupdf.pdf_insert_page(pdfout, -1, page_obj)
i += incr
# PDF created - now write it to Python bytearray
# prepare write options structure
opts = mupdf.PdfWriteOptions()
opts.do_garbage = 4
opts.do_compress = 1
opts.do_compress_images = 1
opts.do_compress_fonts = 1
opts.do_sanitize = 1
opts.do_incremental = 0
opts.do_ascii = 0
opts.do_decompress = 0
opts.do_linear = 0
opts.do_clean = 1
opts.do_pretty = 0
res = mupdf.fz_new_buffer(8192)
out = mupdf.FzOutput(res)
mupdf.pdf_write_document(pdfout, out, opts)
out.fz_close_output()
c = mupdf.fz_buffer_extract_copy(res)
assert isinstance(c, bytes)
return c
# Copied from MuPDF v1.14
# Create widget
def JM_create_widget(doc, page, type, fieldname):
old_sigflags = mupdf.pdf_to_int(mupdf.pdf_dict_getp(mupdf.pdf_trailer(doc), "Root/AcroForm/SigFlags"))
#log( '*** JM_create_widget()')
#log( f'{mupdf.pdf_create_annot_raw=}')
#log( f'{page=}')
#log( f'{mupdf.PDF_ANNOT_WIDGET=}')
annot = mupdf.pdf_create_annot_raw(page, mupdf.PDF_ANNOT_WIDGET)
annot_obj = mupdf.pdf_annot_obj(annot)
try:
JM_set_field_type(doc, annot_obj, type)
mupdf.pdf_dict_put_text_string(annot_obj, PDF_NAME('T'), fieldname)
if type == mupdf.PDF_WIDGET_TYPE_SIGNATURE:
sigflags = old_sigflags | (SigFlag_SignaturesExist | SigFlag_AppendOnly)
mupdf.pdf_dict_putl(
mupdf.pdf_trailer(doc),
mupdf.pdf_new_nt(sigflags),
PDF_NAME('Root'),
PDF_NAME('AcroForm'),
PDF_NAME('SigFlags'),
)
# pdf_create_annot will have linked the new widget into the page's
# annot array. We also need it linked into the document's form
form = mupdf.pdf_dict_getp(mupdf.pdf_trailer(doc), "Root/AcroForm/Fields")
if not form.m_internal:
form = mupdf.pdf_new_array(doc, 1)
mupdf.pdf_dict_putl(
mupdf.pdf_trailer(doc),
form,
PDF_NAME('Root'),
PDF_NAME('AcroForm'),
PDF_NAME('Fields'),
)
mupdf.pdf_array_push(form, annot_obj) # Cleanup relies on this statement being last
except Exception:
if g_exceptions_verbose: exception_info()
mupdf.pdf_delete_annot(page, annot)
if type == mupdf.PDF_WIDGET_TYPE_SIGNATURE:
mupdf.pdf_dict_putl(
mupdf.pdf_trailer(doc),
mupdf.pdf_new_int(old_sigflags),
PDF_NAME('Root'),
PDF_NAME('AcroForm'),
PDF_NAME('SigFlags'),
)
raise
return annot
def JM_cropbox(page_obj):
'''
return a PDF page's CropBox
'''
if g_use_extra:
return extra.JM_cropbox(page_obj)
mediabox = JM_mediabox(page_obj)
cropbox = mupdf.pdf_to_rect(
mupdf.pdf_dict_get_inheritable(page_obj, PDF_NAME('CropBox'))
)
if mupdf.fz_is_infinite_rect(cropbox) or mupdf.fz_is_empty_rect(cropbox):
cropbox = mediabox
y0 = mediabox.y1 - cropbox.y1
y1 = mediabox.y1 - cropbox.y0
cropbox.y0 = y0
cropbox.y1 = y1
return cropbox
def JM_cropbox_size(page_obj):
rect = JM_cropbox(page_obj)
w = abs(rect.x1 - rect.x0)
h = abs(rect.y1 - rect.y0)
size = mupdf.fz_make_point(w, h)
return size
def JM_derotate_page_matrix(page):
'''
just the inverse of rotation
'''
mp = JM_rotate_page_matrix(page)
return mupdf.fz_invert_matrix(mp)
def JM_embed_file(
pdf,
buf,
filename,
ufilename,
desc,
compress,
):
'''
embed a new file in a PDF (not only /EmbeddedFiles entries)
'''
len_ = 0
val = mupdf.pdf_new_dict(pdf, 6)
mupdf.pdf_dict_put_dict(val, PDF_NAME('CI'), 4)
ef = mupdf.pdf_dict_put_dict(val, PDF_NAME('EF'), 4)
mupdf.pdf_dict_put_text_string(val, PDF_NAME('F'), filename)
mupdf.pdf_dict_put_text_string(val, PDF_NAME('UF'), ufilename)
mupdf.pdf_dict_put_text_string(val, PDF_NAME('Desc'), desc)
mupdf.pdf_dict_put(val, PDF_NAME('Type'), PDF_NAME('Filespec'))
bs = b' '
f = mupdf.pdf_add_stream(
pdf,
#mupdf.fz_fz_new_buffer_from_copied_data(bs),
mupdf.fz_new_buffer_from_copied_data(bs),
mupdf.PdfObj(),
0,
)
mupdf.pdf_dict_put(ef, PDF_NAME('F'), f)
JM_update_stream(pdf, f, buf, compress)
len_, _ = mupdf.fz_buffer_storage(buf)
mupdf.pdf_dict_put_int(f, PDF_NAME('DL'), len_)
mupdf.pdf_dict_put_int(f, PDF_NAME('Length'), len_)
params = mupdf.pdf_dict_put_dict(f, PDF_NAME('Params'), 4)
mupdf.pdf_dict_put_int(params, PDF_NAME('Size'), len_)
return val
def JM_embedded_clean(pdf):
'''
perform some cleaning if we have /EmbeddedFiles:
(1) remove any /Limits if /Names exists
(2) remove any empty /Collection
(3) set /PageMode/UseAttachments
'''
root = mupdf.pdf_dict_get( mupdf.pdf_trailer( pdf), PDF_NAME('Root'))
# remove any empty /Collection entry
coll = mupdf.pdf_dict_get(root, PDF_NAME('Collection'))
if coll.m_internal and mupdf.pdf_dict_len(coll) == 0:
mupdf.pdf_dict_del(root, PDF_NAME('Collection'))
efiles = mupdf.pdf_dict_getl(
root,
PDF_NAME('Names'),
PDF_NAME('EmbeddedFiles'),
PDF_NAME('Names'),
)
if efiles.m_internal:
mupdf.pdf_dict_put_name(root, PDF_NAME('PageMode'), "UseAttachments")
def JM_EscapeStrFromBuffer(buff):
if not buff.m_internal:
return ''
s = mupdf.fz_buffer_extract_copy(buff)
val = PyUnicode_DecodeRawUnicodeEscape(s, errors='replace')
return val
def JM_ensure_identity(pdf):
'''
Store ID in PDF trailer
'''
id_ = mupdf.pdf_dict_get( mupdf.pdf_trailer(pdf), PDF_NAME('ID'))
if not id_.m_internal:
rnd0 = mupdf.fz_memrnd2(16)
# Need to convert raw bytes into a str to send to
# mupdf.pdf_new_string(). chr() seems to work for this.
rnd = ''
for i in rnd0:
rnd += chr(i)
id_ = mupdf.pdf_dict_put_array( mupdf.pdf_trailer( pdf), PDF_NAME('ID'), 2)
mupdf.pdf_array_push( id_, mupdf.pdf_new_string( rnd, len(rnd)))
mupdf.pdf_array_push( id_, mupdf.pdf_new_string( rnd, len(rnd)))
def JM_ensure_ocproperties(pdf):
'''
Ensure OCProperties, return /OCProperties key
'''
ocp = mupdf.pdf_dict_get(mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root')), PDF_NAME('OCProperties'))
if ocp.m_internal:
return ocp
root = mupdf.pdf_dict_get(mupdf.pdf_trailer(pdf), PDF_NAME('Root'))
ocp = mupdf.pdf_dict_put_dict(root, PDF_NAME('OCProperties'), 2)
mupdf.pdf_dict_put_array(ocp, PDF_NAME('OCGs'), 0)
D = mupdf.pdf_dict_put_dict(ocp, PDF_NAME('D'), 5)
mupdf.pdf_dict_put_array(D, PDF_NAME('ON'), 0)
mupdf.pdf_dict_put_array(D, PDF_NAME('OFF'), 0)
mupdf.pdf_dict_put_array(D, PDF_NAME('Order'), 0)
mupdf.pdf_dict_put_array(D, PDF_NAME('RBGroups'), 0)
return ocp
def JM_expand_fname(name):
'''
Make /DA string of annotation
'''
if not name: return "Helv"
if name.startswith("Co"): return "Cour"
if name.startswith("co"): return "Cour"
if name.startswith("Ti"): return "TiRo"
if name.startswith("ti"): return "TiRo"
if name.startswith("Sy"): return "Symb"
if name.startswith("sy"): return "Symb"
if name.startswith("Za"): return "ZaDb"
if name.startswith("za"): return "ZaDb"
return "Helv"
def JM_field_type_text(wtype):
'''
String from widget type
'''
if wtype == mupdf.PDF_WIDGET_TYPE_BUTTON:
return "Button"
if wtype == mupdf.PDF_WIDGET_TYPE_CHECKBOX:
return "CheckBox"
if wtype == mupdf.PDF_WIDGET_TYPE_RADIOBUTTON:
return "RadioButton"
if wtype == mupdf.PDF_WIDGET_TYPE_TEXT:
return "Text"
if wtype == mupdf.PDF_WIDGET_TYPE_LISTBOX:
return "ListBox"
if wtype == mupdf.PDF_WIDGET_TYPE_COMBOBOX:
return "ComboBox"
if wtype == mupdf.PDF_WIDGET_TYPE_SIGNATURE:
return "Signature"
return "unknown"
def JM_fill_pixmap_rect_with_color(dest, col, b):
assert isinstance(dest, mupdf.FzPixmap)
# fill a rect with a color tuple
b = mupdf.fz_intersect_irect(b, mupdf.fz_pixmap_bbox( dest))
w = b.x1 - b.x0
y = b.y1 - b.y0
if w <= 0 or y <= 0:
return 0
destspan = dest.stride()
destp = destspan * (b.y0 - dest.y()) + dest.n() * (b.x0 - dest.x())
while 1:
s = destp
for x in range(w):
for i in range( dest.n()):
mupdf.fz_samples_set(dest, s, col[i])
s += 1
destp += destspan
y -= 1
if y == 0:
break
return 1
def JM_find_annot_irt(annot):
'''
Return the first annotation whose /IRT key ("In Response To") points to
annot. Used to remove the response chain of a given annotation.
'''
assert isinstance(annot, mupdf.PdfAnnot)
irt_annot = None # returning this
annot_obj = mupdf.pdf_annot_obj(annot)
found = 0
# loop thru MuPDF's internal annots array
page = mupdf.pdf_annot_page(annot)
irt_annot = mupdf.pdf_first_annot(page)
while 1:
assert isinstance(irt_annot, mupdf.PdfAnnot)
if not irt_annot.m_internal:
break
irt_annot_obj = mupdf.pdf_annot_obj(irt_annot)
o = mupdf.pdf_dict_gets(irt_annot_obj, 'IRT')
if o.m_internal:
if not mupdf.pdf_objcmp(o, annot_obj):
found = 1
break
irt_annot = mupdf.pdf_next_annot(irt_annot)
if found:
return irt_annot
def JM_font_ascender(font):
'''
need own versions of ascender / descender
'''
assert isinstance(font, mupdf.FzFont)
if _globals.skip_quad_corrections:
return 0.8
return mupdf.fz_font_ascender(font)
def JM_font_descender(font):
'''
need own versions of ascender / descender
'''
assert isinstance(font, mupdf.FzFont)
if _globals.skip_quad_corrections:
return -0.2
ret = mupdf.fz_font_descender(font)
return ret
def JM_is_word_delimiter(ch, delimiters):
"""Check if ch is an extra word delimiting character.
"""
if ch <= 32 or ch == 160: # any whitespace?
return True
if not delimiters: # no extra delimiters provided
return False
char = chr(ch)
for d in delimiters:
if d == char:
return True
return False
def JM_font_name(font):
assert isinstance(font, mupdf.FzFont)
name = mupdf.fz_font_name(font)
s = name.find('+')
if _globals.subset_fontnames or s == -1 or s != 6:
return name
return name[s + 1:]
def JM_gather_fonts(pdf, dict_, fontlist, stream_xref):
rc = 1
n = mupdf.pdf_dict_len(dict_)
for i in range(n):
refname = mupdf.pdf_dict_get_key(dict_, i)
fontdict = mupdf.pdf_dict_get_val(dict_, i)
if not mupdf.pdf_is_dict(fontdict):
mupdf.fz_warn( f"'{mupdf.pdf_to_name(refname)}' is no font dict ({mupdf.pdf_to_num(fontdict)} 0 R)")
continue
subtype = mupdf.pdf_dict_get(fontdict, mupdf.PDF_ENUM_NAME_Subtype)
basefont = mupdf.pdf_dict_get(fontdict, mupdf.PDF_ENUM_NAME_BaseFont)
if not basefont.m_internal or mupdf.pdf_is_null(basefont):
name = mupdf.pdf_dict_get(fontdict, mupdf.PDF_ENUM_NAME_Name)
else:
name = basefont
encoding = mupdf.pdf_dict_get(fontdict, mupdf.PDF_ENUM_NAME_Encoding)
if mupdf.pdf_is_dict(encoding):
encoding = mupdf.pdf_dict_get(encoding, mupdf.PDF_ENUM_NAME_BaseEncoding)
xref = mupdf.pdf_to_num(fontdict)
ext = "n/a"
if xref:
ext = JM_get_fontextension(pdf, xref)
entry = (
xref,
ext,
mupdf.pdf_to_name(subtype),
JM_EscapeStrFromStr(mupdf.pdf_to_name(name)),
mupdf.pdf_to_name(refname),
mupdf.pdf_to_name(encoding),
stream_xref,
)
fontlist.append(entry)
return rc
def JM_gather_forms(doc, dict_: mupdf.PdfObj, imagelist, stream_xref: int):
'''
Store info of a /Form xobject in Python list
'''
assert isinstance(doc, mupdf.PdfDocument)
rc = 1
n = mupdf.pdf_dict_len(dict_)
for i in range(n):
refname = mupdf.pdf_dict_get_key( dict_, i)
imagedict = mupdf.pdf_dict_get_val(dict_, i)
if not mupdf.pdf_is_dict(imagedict):
mupdf.fz_warn( f"'{mupdf.pdf_to_name(refname)}' is no form dict ({mupdf.pdf_to_num(imagedict)} 0 R)")
continue
type_ = mupdf.pdf_dict_get(imagedict, PDF_NAME('Subtype'))
if not mupdf.pdf_name_eq(type_, PDF_NAME('Form')):
continue
o = mupdf.pdf_dict_get(imagedict, PDF_NAME('BBox'))
m = mupdf.pdf_dict_get(imagedict, PDF_NAME('Matrix'))
if m.m_internal:
mat = mupdf.pdf_to_matrix(m)
else:
mat = mupdf.FzMatrix()
if o.m_internal:
bbox = mupdf.fz_transform_rect( mupdf.pdf_to_rect(o), mat)
else:
bbox = mupdf.FzRect(mupdf.FzRect.Fixed_INFINITE)
xref = mupdf.pdf_to_num(imagedict)
entry = (
xref,
mupdf.pdf_to_name( refname),
stream_xref,
JM_py_from_rect(bbox),
)
imagelist.append(entry)
return rc
def JM_gather_images(doc: mupdf.PdfDocument, dict_: mupdf.PdfObj, imagelist, stream_xref: int):
'''
Store info of an image in Python list
'''
rc = 1
n = mupdf.pdf_dict_len( dict_)
for i in range(n):
refname = mupdf.pdf_dict_get_key(dict_, i)
imagedict = mupdf.pdf_dict_get_val(dict_, i)
if not mupdf.pdf_is_dict(imagedict):
mupdf.fz_warn(f"'{mupdf.pdf_to_name(refname)}' is no image dict ({mupdf.pdf_to_num(imagedict)} 0 R)")
continue
type_ = mupdf.pdf_dict_get(imagedict, PDF_NAME('Subtype'))
if not mupdf.pdf_name_eq(type_, PDF_NAME('Image')):
continue
xref = mupdf.pdf_to_num(imagedict)
gen = 0
smask = mupdf.pdf_dict_geta(imagedict, PDF_NAME('SMask'), PDF_NAME('Mask'))
if smask.m_internal:
gen = mupdf.pdf_to_num(smask)
filter_ = mupdf.pdf_dict_geta(imagedict, PDF_NAME('Filter'), PDF_NAME('F'))
if mupdf.pdf_is_array(filter_):
filter_ = mupdf.pdf_array_get(filter_, 0)
altcs = mupdf.PdfObj(0)
cs = mupdf.pdf_dict_geta(imagedict, PDF_NAME('ColorSpace'), PDF_NAME('CS'))
if mupdf.pdf_is_array(cs):
cses = cs
cs = mupdf.pdf_array_get(cses, 0)
if (mupdf.pdf_name_eq(cs, PDF_NAME('DeviceN'))
or mupdf.pdf_name_eq(cs, PDF_NAME('Separation'))
):
altcs = mupdf.pdf_array_get(cses, 2)
if mupdf.pdf_is_array(altcs):
altcs = mupdf.pdf_array_get(altcs, 0)
width = mupdf.pdf_dict_geta(imagedict, PDF_NAME('Width'), PDF_NAME('W'))
height = mupdf.pdf_dict_geta(imagedict, PDF_NAME('Height'), PDF_NAME('H'))
bpc = mupdf.pdf_dict_geta(imagedict, PDF_NAME('BitsPerComponent'), PDF_NAME('BPC'))
entry = (
xref,
gen,
mupdf.pdf_to_int(width),
mupdf.pdf_to_int(height),
mupdf.pdf_to_int(bpc),
JM_EscapeStrFromStr(mupdf.pdf_to_name(cs)),
JM_EscapeStrFromStr(mupdf.pdf_to_name(altcs)),
JM_EscapeStrFromStr(mupdf.pdf_to_name(refname)),
JM_EscapeStrFromStr(mupdf.pdf_to_name(filter_)),
stream_xref,
)
imagelist.append(entry)
return rc
def JM_get_annot_by_xref(page, xref):
'''
retrieve annot by its xref
'''
assert isinstance(page, mupdf.PdfPage)
found = 0
# loop thru MuPDF's internal annots array
annot = mupdf.pdf_first_annot(page)
while 1:
if not annot.m_internal:
break
if xref == mupdf.pdf_to_num(mupdf.pdf_annot_obj(annot)):
found = 1
break
annot = mupdf.pdf_next_annot( annot)
if not found:
raise Exception("xref %d is not an annot of this page" % xref)
return annot
def JM_get_annot_by_name(page, name):
'''
retrieve annot by name (/NM key)
'''
assert isinstance(page, mupdf.PdfPage)
if not name:
return
found = 0
# loop thru MuPDF's internal annots and widget arrays
annot = mupdf.pdf_first_annot(page)
while 1:
if not annot.m_internal:
break
response, len_ = mupdf.pdf_to_string(mupdf.pdf_dict_gets(mupdf.pdf_annot_obj(annot), "NM"))
if name == response:
found = 1
break
annot = mupdf.pdf_next_annot(annot)
if not found:
raise Exception("'%s' is not an annot of this page" % name)
return annot
def JM_get_annot_id_list(page):
names = []
annots = mupdf.pdf_dict_get( page.obj(), mupdf.PDF_ENUM_NAME_Annots)
if not annots.m_internal:
return names
for i in range( mupdf.pdf_array_len(annots)):
annot_obj = mupdf.pdf_array_get(annots, i)
name = mupdf.pdf_dict_gets(annot_obj, "NM")
if name.m_internal:
names.append(
mupdf.pdf_to_text_string(name)
)
return names
def JM_get_annot_xref_list( page_obj):
'''
return the xrefs and /NM ids of a page's annots, links and fields
'''
if g_use_extra:
names = extra.JM_get_annot_xref_list( page_obj)
return names
names = []
annots = mupdf.pdf_dict_get( page_obj, PDF_NAME('Annots'))
n = mupdf.pdf_array_len( annots)
for i in range( n):
annot_obj = mupdf.pdf_array_get( annots, i)
xref = mupdf.pdf_to_num( annot_obj)
subtype = mupdf.pdf_dict_get( annot_obj, PDF_NAME('Subtype'))
if not subtype.m_internal:
continue # subtype is required
type_ = mupdf.pdf_annot_type_from_string( mupdf.pdf_to_name( subtype))
if type_ == mupdf.PDF_ANNOT_UNKNOWN:
continue # only accept valid annot types
id_ = mupdf.pdf_dict_gets( annot_obj, "NM")
names.append( (xref, type_, mupdf.pdf_to_text_string( id_)))
return names
def JM_get_annot_xref_list2(page):
page = page._pdf_page(required=False)
if not page.m_internal:
return list()
return JM_get_annot_xref_list( page.obj())
def JM_get_border_style(style):
'''
return pdf_obj "border style" from Python str
'''
val = mupdf.PDF_ENUM_NAME_S
if style is None:
return val
s = style
if s.startswith("b") or s.startswith("B"): val = mupdf.PDF_ENUM_NAME_B
elif s.startswith("d") or s.startswith("D"): val = mupdf.PDF_ENUM_NAME_D
elif s.startswith("i") or s.startswith("I"): val = mupdf.PDF_ENUM_NAME_I
elif s.startswith("u") or s.startswith("U"): val = mupdf.PDF_ENUM_NAME_U
elif s.startswith("s") or s.startswith("S"): val = mupdf.PDF_ENUM_NAME_S
return val
def JM_get_font(
fontname,
fontfile,
fontbuffer,
script,
lang,
ordering,
is_bold,
is_italic,
is_serif,
embed,
):
'''
return a fz_font from a number of parameters
'''
def fertig(font):
if not font.m_internal:
raise RuntimeError(MSG_FONT_FAILED)
# if font allows this, set embedding
if not font.m_internal.flags.never_embed:
mupdf.fz_set_font_embedding(font, embed)
return font
index = 0
font = None
if fontfile:
#goto have_file;
font = mupdf.fz_new_font_from_file( None, fontfile, index, 0)
return fertig(font)
if fontbuffer:
#goto have_buffer;
res = JM_BufferFromBytes(fontbuffer)
font = mupdf.fz_new_font_from_buffer( None, res, index, 0)
return fertig(font)
if ordering > -1:
# goto have_cjk;
font = mupdf.fz_new_cjk_font(ordering)
return fertig(font)
if fontname:
# goto have_base14;
# Base-14 or a MuPDF builtin font
font = mupdf.fz_new_base14_font(fontname)
if font.m_internal:
return fertig(font)
font = mupdf.fz_new_builtin_font(fontname, is_bold, is_italic)
return fertig(font)
# Check for NOTO font
#have_noto:;
data, size, index = mupdf.fz_lookup_noto_font( script, lang)
font = None
if data:
font = mupdf.fz_new_font_from_memory( None, data, size, index, 0)
if font.m_internal:
return fertig(font)
font = mupdf.fz_load_fallback_font( script, lang, is_serif, is_bold, is_italic)
return fertig(font)
def JM_get_fontbuffer(doc, xref):
'''
Return the contents of a font file, identified by xref
'''
if xref < 1:
return
o = mupdf.pdf_load_object(doc, xref)
desft = mupdf.pdf_dict_get(o, PDF_NAME('DescendantFonts'))
if desft.m_internal:
obj = mupdf.pdf_resolve_indirect(mupdf.pdf_array_get(desft, 0))
obj = mupdf.pdf_dict_get(obj, PDF_NAME('FontDescriptor'))
else:
obj = mupdf.pdf_dict_get(o, PDF_NAME('FontDescriptor'))
if not obj.m_internal:
message(f"invalid font - FontDescriptor missing")
return
o = obj
stream = None
obj = mupdf.pdf_dict_get(o, PDF_NAME('FontFile'))
if obj.m_internal:
stream = obj # ext = "pfa"
obj = mupdf.pdf_dict_get(o, PDF_NAME('FontFile2'))
if obj.m_internal:
stream = obj # ext = "ttf"
obj = mupdf.pdf_dict_get(o, PDF_NAME('FontFile3'))
if obj.m_internal:
stream = obj
obj = mupdf.pdf_dict_get(obj, PDF_NAME('Subtype'))
if obj.m_internal and not mupdf.pdf_is_name(obj):
message("invalid font descriptor subtype")
return
if mupdf.pdf_name_eq(obj, PDF_NAME('Type1C')):
pass # Prev code did: ext = "cff", but this has no effect.
elif mupdf.pdf_name_eq(obj, PDF_NAME('CIDFontType0C')):
pass # Prev code did: ext = "cid", but this has no effect.
elif mupdf.pdf_name_eq(obj, PDF_NAME('OpenType')):
pass # Prev code did: ext = "otf", but this has no effect. */
else:
message('warning: unhandled font type {pdf_to_name(ctx, obj)!r}')
if not stream:
message('warning: unhandled font type')
return
return mupdf.pdf_load_stream(stream)
def JM_get_resource_properties(ref):
'''
Return the items of Resources/Properties (used for Marked Content)
Argument may be e.g. a page object or a Form XObject
'''
properties = mupdf.pdf_dict_getl(ref, PDF_NAME('Resources'), PDF_NAME('Properties'))
if not properties.m_internal:
return ()
else:
n = mupdf.pdf_dict_len(properties)
if n < 1:
return ()
rc = []
for i in range(n):
key = mupdf.pdf_dict_get_key(properties, i)
val = mupdf.pdf_dict_get_val(properties, i)
c = mupdf.pdf_to_name(key)
xref = mupdf.pdf_to_num(val)
rc.append((c, xref))
return rc
def JM_get_widget_by_xref( page, xref):
'''
retrieve widget by its xref
'''
found = False
annot = mupdf.pdf_first_widget( page)
while annot.m_internal:
annot_obj = mupdf.pdf_annot_obj( annot)
if xref == mupdf.pdf_to_num( annot_obj):
found = True
break
annot = mupdf.pdf_next_widget( annot)
if not found:
raise Exception( f"xref {xref} is not a widget of this page")
return Annot( annot)
def JM_get_widget_properties(annot, Widget):
'''
Populate a Python Widget object with the values from a PDF form field.
Called by "Page.first_widget" and "Widget.next".
'''
#log( '{type(annot)=}')
annot_obj = mupdf.pdf_annot_obj(annot.this)
#log( 'Have called mupdf.pdf_annot_obj()')
page = mupdf.pdf_annot_page(annot.this)
pdf = page.doc()
tw = annot
def SETATTR(key, value):
setattr(Widget, key, value)
def SETATTR_DROP(mod, key, value):
# Original C code for this function deletes if PyObject* is NULL. We
# don't have a representation for that in Python - e.g. None is not
# represented by NULL.
setattr(mod, key, value)
#log( '=== + mupdf.pdf_widget_type(tw)')
field_type = mupdf.pdf_widget_type(tw.this)
#log( '=== - mupdf.pdf_widget_type(tw)')
Widget.field_type = field_type
if field_type == mupdf.PDF_WIDGET_TYPE_SIGNATURE:
if mupdf.pdf_signature_is_signed(pdf, annot_obj):
SETATTR("is_signed", True)
else:
SETATTR("is_signed",False)
else:
SETATTR("is_signed", None)
SETATTR_DROP(Widget, "border_style", JM_UnicodeFromStr(mupdf.pdf_field_border_style(annot_obj)))
SETATTR_DROP(Widget, "field_type_string", JM_UnicodeFromStr(JM_field_type_text(field_type)))
field_name = mupdf.pdf_load_field_name(annot_obj)
SETATTR_DROP(Widget, "field_name", field_name)
def pdf_dict_get_inheritable_nonempty_label(node, key):
'''
This is a modified version of MuPDF's pdf_dict_get_inheritable(), with
some changes:
* Returns string from pdf_to_text_string() or None if not found.
* Recurses to parent if current node exists but with empty string
value.
'''
slow = node
halfbeat = 11 # Don't start moving slow pointer for a while.
while 1:
if not node.m_internal:
return
val = mupdf.pdf_dict_get(node, key)
if val.m_internal:
label = mupdf.pdf_to_text_string(val)
if label:
return label
node = mupdf.pdf_dict_get(node, PDF_NAME('Parent'))
if node.m_internal == slow.m_internal:
raise Exception("cycle in resources")
halfbeat -= 1
if halfbeat == 0:
slow = mupdf.pdf_dict_get(slow, PDF_NAME('Parent'))
halfbeat = 2
# In order to address #3950, we use our modified pdf_dict_get_inheritable()
# to ignore empty-string child values.
label = pdf_dict_get_inheritable_nonempty_label(annot_obj, PDF_NAME('TU'))
if label is not None:
SETATTR_DROP(Widget, "field_label", label)
fvalue = None
if field_type == mupdf.PDF_WIDGET_TYPE_RADIOBUTTON:
obj = mupdf.pdf_dict_get( annot_obj, PDF_NAME('Parent')) # owning RB group
if obj.m_internal:
SETATTR_DROP(Widget, "rb_parent", mupdf.pdf_to_num( obj))
obj = mupdf.pdf_dict_get(annot_obj, PDF_NAME('AS'))
if obj.m_internal:
fvalue = mupdf.pdf_to_name(obj)
if not fvalue:
fvalue = mupdf.pdf_field_value(annot_obj)
SETATTR_DROP(Widget, "field_value", JM_UnicodeFromStr(fvalue))
SETATTR_DROP(Widget, "field_display", mupdf.pdf_field_display(annot_obj))
border_width = mupdf.pdf_to_real(mupdf.pdf_dict_getl(annot_obj, PDF_NAME('BS'), PDF_NAME('W')))
if border_width == 0:
border_width = 1
SETATTR_DROP(Widget, "border_width", border_width)
obj = mupdf.pdf_dict_getl(annot_obj, PDF_NAME('BS'), PDF_NAME('D'))
if mupdf.pdf_is_array(obj):
n = mupdf.pdf_array_len(obj)
d = [0] * n
for i in range(n):
d[i] = mupdf.pdf_to_int(mupdf.pdf_array_get(obj, i))
SETATTR_DROP(Widget, "border_dashes", d)
SETATTR_DROP(Widget, "text_maxlen", mupdf.pdf_text_widget_max_len(tw.this))
SETATTR_DROP(Widget, "text_format", mupdf.pdf_text_widget_format(tw.this))
obj = mupdf.pdf_dict_getl(annot_obj, PDF_NAME('MK'), PDF_NAME('BG'))
if mupdf.pdf_is_array(obj):
n = mupdf.pdf_array_len(obj)
col = [0] * n
for i in range(n):
col[i] = mupdf.pdf_to_real(mupdf.pdf_array_get(obj, i))
SETATTR_DROP(Widget, "fill_color", col)
obj = mupdf.pdf_dict_getl(annot_obj, PDF_NAME('MK'), PDF_NAME('BC'))
if mupdf.pdf_is_array(obj):
n = mupdf.pdf_array_len(obj)
col = [0] * n
for i in range(n):
col[i] = mupdf.pdf_to_real(mupdf.pdf_array_get(obj, i))
SETATTR_DROP(Widget, "border_color", col)
SETATTR_DROP(Widget, "choice_values", JM_choice_options(annot))
da = mupdf.pdf_to_text_string(mupdf.pdf_dict_get_inheritable(annot_obj, PDF_NAME('DA')))
SETATTR_DROP(Widget, "_text_da", JM_UnicodeFromStr(da))
obj = mupdf.pdf_dict_getl(annot_obj, PDF_NAME('MK'), PDF_NAME('CA'))
if obj.m_internal:
SETATTR_DROP(Widget, "button_caption", JM_UnicodeFromStr(mupdf.pdf_to_text_string(obj)))
SETATTR_DROP(Widget, "field_flags", mupdf.pdf_field_flags(annot_obj))
# call Py method to reconstruct text color, font name, size
Widget._parse_da()
# extract JavaScript action texts
s = mupdf.pdf_dict_get(annot_obj, PDF_NAME('A'))
ss = JM_get_script(s)
SETATTR_DROP(Widget, "script", ss)
SETATTR_DROP(Widget, "script_stroke",
JM_get_script(mupdf.pdf_dict_getl(annot_obj, PDF_NAME('AA'), PDF_NAME('K')))
)
SETATTR_DROP(Widget, "script_format",
JM_get_script(mupdf.pdf_dict_getl(annot_obj, PDF_NAME('AA'), PDF_NAME('F')))
)
SETATTR_DROP(Widget, "script_change",
JM_get_script(mupdf.pdf_dict_getl(annot_obj, PDF_NAME('AA'), PDF_NAME('V')))
)
SETATTR_DROP(Widget, "script_calc",
JM_get_script(mupdf.pdf_dict_getl(annot_obj, PDF_NAME('AA'), PDF_NAME('C')))
)
SETATTR_DROP(Widget, "script_blur",
JM_get_script(mupdf.pdf_dict_getl(annot_obj, PDF_NAME('AA'), mupdf.pdf_new_name('Bl')))
)
SETATTR_DROP(Widget, "script_focus",
JM_get_script(mupdf.pdf_dict_getl(annot_obj, PDF_NAME('AA'), mupdf.pdf_new_name('Fo')))
)
def JM_get_fontextension(doc, xref):
'''
Return the file extension of a font file, identified by xref
'''
if xref < 1:
return "n/a"
o = mupdf.pdf_load_object(doc, xref)
desft = mupdf.pdf_dict_get(o, PDF_NAME('DescendantFonts'))
if desft.m_internal:
obj = mupdf.pdf_resolve_indirect(mupdf.pdf_array_get(desft, 0))
obj = mupdf.pdf_dict_get(obj, PDF_NAME('FontDescriptor'))
else:
obj = mupdf.pdf_dict_get(o, PDF_NAME('FontDescriptor'))
if not obj.m_internal:
return "n/a" # this is a base-14 font
o = obj # we have the FontDescriptor
obj = mupdf.pdf_dict_get(o, PDF_NAME('FontFile'))
if obj.m_internal:
return "pfa"
obj = mupdf.pdf_dict_get(o, PDF_NAME('FontFile2'))
if obj.m_internal:
return "ttf"
obj = mupdf.pdf_dict_get(o, PDF_NAME('FontFile3'))
if obj.m_internal:
obj = mupdf.pdf_dict_get(obj, PDF_NAME('Subtype'))
if obj.m_internal and not mupdf.pdf_is_name(obj):
message("invalid font descriptor subtype")
return "n/a"
if mupdf.pdf_name_eq(obj, PDF_NAME('Type1C')):
return "cff"
elif mupdf.pdf_name_eq(obj, PDF_NAME('CIDFontType0C')):
return "cid"
elif mupdf.pdf_name_eq(obj, PDF_NAME('OpenType')):
return "otf"
else:
message("unhandled font type '%s'", mupdf.pdf_to_name(obj))
return "n/a"
def JM_get_ocg_arrays_imp(arr):
'''
Get OCG arrays from OC configuration
Returns dict {"basestate":name, "on":list, "off":list, "rbg":list, "locked":list}
'''
list_ = list()
if mupdf.pdf_is_array( arr):
n = mupdf.pdf_array_len( arr)
for i in range(n):
obj = mupdf.pdf_array_get( arr, i)
item = mupdf.pdf_to_num( obj)
if item not in list_:
list_.append(item)
return list_
def JM_get_ocg_arrays(conf):
rc = dict()
arr = mupdf.pdf_dict_get( conf, PDF_NAME('ON'))
list_ = JM_get_ocg_arrays_imp( arr)
if list_:
rc["on"] = list_
arr = mupdf.pdf_dict_get( conf, PDF_NAME('OFF'))
list_ = JM_get_ocg_arrays_imp( arr)
if list_:
rc["off"] = list_
arr = mupdf.pdf_dict_get( conf, PDF_NAME('Locked'))
list_ = JM_get_ocg_arrays_imp( arr)
if list_:
rc['locked'] = list_
list_ = list()
arr = mupdf.pdf_dict_get( conf, PDF_NAME('RBGroups'))
if mupdf.pdf_is_array( arr):
n = mupdf.pdf_array_len( arr)
for i in range(n):
obj = mupdf.pdf_array_get( arr, i)
list1 = JM_get_ocg_arrays_imp( obj)
list_.append(list1)
if list_:
rc["rbgroups"] = list_
obj = mupdf.pdf_dict_get( conf, PDF_NAME('BaseState'))
if obj.m_internal:
state = mupdf.pdf_to_name( obj)
rc["basestate"] = state
return rc
def JM_get_page_labels(liste, nums):
n = mupdf.pdf_array_len(nums)
for i in range(0, n, 2):
key = mupdf.pdf_resolve_indirect( mupdf.pdf_array_get(nums, i))
pno = mupdf.pdf_to_int(key)
val = mupdf.pdf_resolve_indirect( mupdf.pdf_array_get(nums, i + 1))
res = JM_object_to_buffer(val, 1, 0)
c = mupdf.fz_buffer_extract(res)
assert isinstance(c, bytes)
c = c.decode('utf-8')
liste.append( (pno, c))
def JM_get_script(key):
'''
JavaScript extractor
Returns either the script source or None. Parameter is a PDF action
dictionary, which must have keys /S and /JS. The value of /S must be
'/JavaScript'. The value of /JS is returned.
'''
if not key.m_internal:
return
j = mupdf.pdf_dict_get(key, PDF_NAME('S'))
jj = mupdf.pdf_to_name(j)
if jj == "JavaScript":
js = mupdf.pdf_dict_get(key, PDF_NAME('JS'))
if not js.m_internal:
return
else:
return
if mupdf.pdf_is_string(js):
script = JM_UnicodeFromStr(mupdf.pdf_to_text_string(js))
elif mupdf.pdf_is_stream(js):
res = mupdf.pdf_load_stream(js)
script = JM_EscapeStrFromBuffer(res)
else:
return
if script: # do not return an empty script
return script
return
def JM_have_operation(pdf):
'''
Ensure valid journalling state
'''
if pdf.m_internal.journal and not mupdf.pdf_undoredo_step(pdf, 0):
return 0
return 1
def JM_image_extension(type_):
'''
return extension for MuPDF image type
'''
if type_ == mupdf.FZ_IMAGE_FAX: return "fax"
if type_ == mupdf.FZ_IMAGE_RAW: return "raw"
if type_ == mupdf.FZ_IMAGE_FLATE: return "flate"
if type_ == mupdf.FZ_IMAGE_LZW: return "lzw"
if type_ == mupdf.FZ_IMAGE_RLD: return "rld"
if type_ == mupdf.FZ_IMAGE_BMP: return "bmp"
if type_ == mupdf.FZ_IMAGE_GIF: return "gif"
if type_ == mupdf.FZ_IMAGE_JBIG2: return "jb2"
if type_ == mupdf.FZ_IMAGE_JPEG: return "jpeg"
if type_ == mupdf.FZ_IMAGE_JPX: return "jpx"
if type_ == mupdf.FZ_IMAGE_JXR: return "jxr"
if type_ == mupdf.FZ_IMAGE_PNG: return "png"
if type_ == mupdf.FZ_IMAGE_PNM: return "pnm"
if type_ == mupdf.FZ_IMAGE_TIFF: return "tiff"
#if type_ == mupdf.FZ_IMAGE_PSD: return "psd"
return "n/a"
# fixme: need to avoid using a global for this.
g_img_info = None
def JM_image_filter(opaque, ctm, name, image):
assert isinstance(ctm, mupdf.FzMatrix)
r = mupdf.FzRect(mupdf.FzRect.Fixed_UNIT)
q = mupdf.fz_transform_quad( mupdf.fz_quad_from_rect(r), ctm)
q = mupdf.fz_transform_quad( q, g_img_info_matrix)
temp = name, JM_py_from_quad(q)
g_img_info.append(temp)
def JM_image_profile( imagedata, keep_image):
'''
Return basic properties of an image provided as bytes or bytearray
The function creates an fz_image and optionally returns it.
'''
if not imagedata:
return None # nothing given
len_ = len( imagedata)
if len_ < 8:
message( "bad image data")
return None
c = imagedata
#log( 'calling mfz_recognize_image_format with {c!r=}')
type_ = mupdf.fz_recognize_image_format( c)
if type_ == mupdf.FZ_IMAGE_UNKNOWN:
return None
if keep_image:
res = mupdf.fz_new_buffer_from_copied_data( c, len_)
else:
res = mupdf.fz_new_buffer_from_shared_data( c, len_)
image = mupdf.fz_new_image_from_buffer( res)
ctm = mupdf.fz_image_orientation_matrix( image)
xres, yres = mupdf.fz_image_resolution(image)
orientation = mupdf.fz_image_orientation( image)
cs_name = mupdf.fz_colorspace_name( image.colorspace())
result = dict()
result[ dictkey_width] = image.w()
result[ dictkey_height] = image.h()
result[ "orientation"] = orientation
result[ dictkey_matrix] = JM_py_from_matrix(ctm)
result[ dictkey_xres] = xres
result[ dictkey_yres] = yres
result[ dictkey_colorspace] = image.n()
result[ dictkey_bpc] = image.bpc()
result[ dictkey_ext] = JM_image_extension(type_)
result[ dictkey_cs_name] = cs_name
if keep_image:
result[ dictkey_image] = image
return result
def JM_image_reporter(page):
doc = page.doc()
global g_img_info_matrix
g_img_info_matrix = mupdf.FzMatrix()
mediabox = mupdf.FzRect()
mupdf.pdf_page_transform(page, mediabox, g_img_info_matrix)
class SanitizeFilterOptions(mupdf.PdfSanitizeFilterOptions2):
def __init__(self):
super().__init__()
self.use_virtual_image_filter()
if mupdf_version_tuple >= (1, 23, 11):
def image_filter(self, ctx, ctm, name, image, scissor):
JM_image_filter(None, mupdf.FzMatrix(ctm), name, image)
else:
def image_filter(self, ctx, ctm, name, image):
JM_image_filter(None, mupdf.FzMatrix(ctm), name, image)
sanitize_filter_options = SanitizeFilterOptions()
filter_options = _make_PdfFilterOptions(
instance_forms=1,
ascii=1,
no_update=1,
sanitize=1,
sopts=sanitize_filter_options,
)
global g_img_info
g_img_info = []
mupdf.pdf_filter_page_contents( doc, page, filter_options)
rc = tuple(g_img_info)
g_img_info = []
return rc
def JM_fitz_config():
have_TOFU = not hasattr(mupdf, 'TOFU')
have_TOFU_BASE14 = not hasattr(mupdf, 'TOFU_BASE14')
have_TOFU_CJK = not hasattr(mupdf, 'TOFU_CJK')
have_TOFU_CJK_EXT = not hasattr(mupdf, 'TOFU_CJK_EXT')
have_TOFU_CJK_LANG = not hasattr(mupdf, 'TOFU_CJK_LANG')
have_TOFU_EMOJI = not hasattr(mupdf, 'TOFU_EMOJI')
have_TOFU_HISTORIC = not hasattr(mupdf, 'TOFU_HISTORIC')
have_TOFU_SIL = not hasattr(mupdf, 'TOFU_SIL')
have_TOFU_SYMBOL = not hasattr(mupdf, 'TOFU_SYMBOL')
ret = dict()
ret["base14"] = have_TOFU_BASE14
ret["cbz"] = bool(mupdf.FZ_ENABLE_CBZ)
ret["epub"] = bool(mupdf.FZ_ENABLE_EPUB)
ret["html"] = bool(mupdf.FZ_ENABLE_HTML)
ret["icc"] = bool(mupdf.FZ_ENABLE_ICC)
ret["img"] = bool(mupdf.FZ_ENABLE_IMG)
ret["jpx"] = bool(mupdf.FZ_ENABLE_JPX)
ret["js"] = bool(mupdf.FZ_ENABLE_JS)
ret["pdf"] = bool(mupdf.FZ_ENABLE_PDF)
ret["plotter-cmyk"] = bool(mupdf.FZ_PLOTTERS_CMYK)
ret["plotter-g"] = bool(mupdf.FZ_PLOTTERS_G)
ret["plotter-n"] = bool(mupdf.FZ_PLOTTERS_N)
ret["plotter-rgb"] = bool(mupdf.FZ_PLOTTERS_RGB)
ret["py-memory"] = bool(JM_MEMORY)
ret["svg"] = bool(mupdf.FZ_ENABLE_SVG)
ret["tofu"] = have_TOFU
ret["tofu-cjk"] = have_TOFU_CJK
ret["tofu-cjk-ext"] = have_TOFU_CJK_EXT
ret["tofu-cjk-lang"] = have_TOFU_CJK_LANG
ret["tofu-emoji"] = have_TOFU_EMOJI
ret["tofu-historic"] = have_TOFU_HISTORIC
ret["tofu-sil"] = have_TOFU_SIL
ret["tofu-symbol"] = have_TOFU_SYMBOL
ret["xps"] = bool(mupdf.FZ_ENABLE_XPS)
return ret
def JM_insert_contents(pdf, pageref, newcont, overlay):
'''
Insert a buffer as a new separate /Contents object of a page.
1. Create a new stream object from buffer 'newcont'
2. If /Contents already is an array, then just prepend or append this object
3. Else, create new array and put old content obj and this object into it.
If the page had no /Contents before, just create a 1-item array.
'''
contents = mupdf.pdf_dict_get(pageref, PDF_NAME('Contents'))
newconts = mupdf.pdf_add_stream(pdf, newcont, mupdf.PdfObj(), 0)
xref = mupdf.pdf_to_num(newconts)
if mupdf.pdf_is_array(contents):
if overlay: # append new object
mupdf.pdf_array_push(contents, newconts)
else: # prepend new object
mupdf.pdf_array_insert(contents, newconts, 0)
else:
carr = mupdf.pdf_new_array(pdf, 5)
if overlay:
if contents.m_internal:
mupdf.pdf_array_push(carr, contents)
mupdf.pdf_array_push(carr, newconts)
else:
mupdf.pdf_array_push(carr, newconts)
if contents.m_internal:
mupdf.pdf_array_push(carr, contents)
mupdf.pdf_dict_put(pageref, PDF_NAME('Contents'), carr)
return xref
def JM_insert_font(pdf, bfname, fontfile, fontbuffer, set_simple, idx, wmode, serif, encoding, ordering):
'''
Insert a font in a PDF
'''
font = None
res = None
data = None
ixref = 0
index = 0
simple = 0
value=None
name=None
subt=None
exto = None
ENSURE_OPERATION(pdf)
# check for CJK font
if ordering > -1:
data, size, index = mupdf.fz_lookup_cjk_font(ordering)
if data:
font = mupdf.fz_new_font_from_memory(None, data, size, index, 0)
font_obj = mupdf.pdf_add_cjk_font(pdf, font, ordering, wmode, serif)
exto = "n/a"
simple = 0
#goto weiter;
else:
# check for PDF Base-14 font
if bfname:
data, size = mupdf.fz_lookup_base14_font(bfname)
if data:
font = mupdf.fz_new_font_from_memory(bfname, data, size, 0, 0)
font_obj = mupdf.pdf_add_simple_font(pdf, font, encoding)
exto = "n/a"
simple = 1
#goto weiter;
else:
if fontfile:
font = mupdf.fz_new_font_from_file(None, fontfile, idx, 0)
else:
res = JM_BufferFromBytes(fontbuffer)
if not res.m_internal:
RAISEPY(MSG_FILE_OR_BUFFER, PyExc_ValueError)
font = mupdf.fz_new_font_from_buffer(None, res, idx, 0)
if not set_simple:
font_obj = mupdf.pdf_add_cid_font(pdf, font)
simple = 0
else:
font_obj = mupdf.pdf_add_simple_font(pdf, font, encoding)
simple = 2
#weiter: ;
ixref = mupdf.pdf_to_num(font_obj)
name = JM_EscapeStrFromStr( mupdf.pdf_to_name( mupdf.pdf_dict_get(font_obj, PDF_NAME('BaseFont'))))
subt = JM_UnicodeFromStr( mupdf.pdf_to_name( mupdf.pdf_dict_get( font_obj, PDF_NAME('Subtype'))))
if not exto:
exto = JM_UnicodeFromStr(JM_get_fontextension(pdf, ixref))
asc = mupdf.fz_font_ascender(font)
dsc = mupdf.fz_font_descender(font)
value = [
ixref,
{
"name": name, # base font name
"type": subt, # subtype
"ext": exto, # file extension
"simple": bool(simple), # simple font?
"ordering": ordering, # CJK font?
"ascender": asc,
"descender": dsc,
},
]
return value
def JM_invert_pixmap_rect( dest, b):
'''
invert a rectangle - also supports non-alpha pixmaps
'''
assert isinstance( dest, mupdf.FzPixmap)
assert isinstance( b, mupdf.FzIrect)
b = mupdf.fz_intersect_irect(b, mupdf.fz_pixmap_bbox( dest))
w = b.x1 - b.x0
y = b.y1 - b.y0
if w <= 0 or y <= 0:
return 0
destspan = dest.stride()
destp = destspan * (b.y0 - dest.y()) + dest.n() * (b.x0 - dest.x())
n0 = dest.n() - dest.alpha()
alpha = dest.alpha()
while 1:
s = destp
for x in range( w):
for i in range( n0):
ss = mupdf.fz_samples_get( dest, s)
ss = 255 - ss
mupdf.fz_samples_set( dest, s, ss)
s += 1
if alpha:
ss = mupdf.fz_samples_get( dest, s)
ss += 1
mupdf.fz_samples_set( dest, s, ss)
destp += destspan
y -= 1
if y == 0:
break
return 1
def JM_irect_from_py(r):
'''
PySequence to mupdf.FzIrect. Default: infinite irect
'''
if isinstance(r, mupdf.FzIrect):
return r
if isinstance(r, IRect):
r = mupdf.FzIrect( r.x0, r.y0, r.x1, r.y1)
return r
if isinstance(r, Rect):
ret = mupdf.FzRect(r.x0, r.y0, r.x1, r.y1)
ret = mupdf.FzIrect(ret) # Uses fz_irect_from_rect().
return ret
if isinstance(r, mupdf.FzRect):
ret = mupdf.FzIrect(r) # Uses fz_irect_from_rect().
return ret
if not r or not PySequence_Check(r) or PySequence_Size(r) != 4:
return mupdf.FzIrect(mupdf.fz_infinite_irect)
f = [0, 0, 0, 0]
for i in range(4):
f[i] = r[i]
if f[i] is None:
return mupdf.FzIrect(mupdf.fz_infinite_irect)
if f[i] < FZ_MIN_INF_RECT:
f[i] = FZ_MIN_INF_RECT
if f[i] > FZ_MAX_INF_RECT:
f[i] = FZ_MAX_INF_RECT
return mupdf.fz_make_irect(f[0], f[1], f[2], f[3])
def JM_is_jbig2_image(dict_):
# fixme: should we remove this function?
return 0
#filter_ = pdf_dict_get(ctx, dict_, PDF_NAME(Filter));
#if (pdf_name_eq(ctx, filter_, PDF_NAME(JBIG2Decode)))
# return 1;
#n = pdf_array_len(ctx, filter_);
#for (i = 0; i < n; i++)
# if (pdf_name_eq(ctx, pdf_array_get(ctx, filter_, i), PDF_NAME(JBIG2Decode)))
# return 1;
#return 0;
def JM_listbox_value( annot):
'''
ListBox retrieve value
'''
# may be single value or array
annot_obj = mupdf.pdf_annot_obj( annot)
optarr = mupdf.pdf_dict_get( annot_obj, PDF_NAME('V'))
if mupdf.pdf_is_string( optarr): # a single string
return mupdf.pdf_to_text_string( optarr)
# value is an array (may have len 0)
n = mupdf.pdf_array_len( optarr)
liste = []
# extract a list of strings
# each entry may again be an array: take second entry then
for i in range( n):
elem = mupdf.pdf_array_get( optarr, i)
if mupdf.pdf_is_array( elem):
elem = mupdf.pdf_array_get( elem, 1)
liste.append( JM_UnicodeFromStr( mupdf.pdf_to_text_string( elem)))
return liste
def JM_make_annot_DA(annot, ncol, col, fontname, fontsize):
# PyMuPDF uses a fz_buffer to build up the string, but it's non-trivial to
# convert the fz_buffer's `unsigned char*` into a `const char*` suitable
# for passing to pdf_dict_put_text_string(). So instead we build up the
# string directly in Python.
buf = ''
if ncol < 1:
buf += f'0 g '
elif ncol == 1:
buf += f'{col[0]:g} g '
elif ncol == 2:
assert 0
elif ncol == 3:
buf += f'{col[0]:g} {col[1]:g} {col[2]:g} rg '
else:
buf += f'{col[0]:g} {col[1]:g} {col[2]:g} {col[3]:g} k '
buf += f'/{JM_expand_fname(fontname)} {fontsize} Tf'
mupdf.pdf_dict_put_text_string(mupdf.pdf_annot_obj(annot), mupdf.PDF_ENUM_NAME_DA, buf)
def JM_make_spanlist(line_dict, line, raw, buff, tp_rect):
if g_use_extra:
return extra.JM_make_spanlist(line_dict, line, raw, buff, tp_rect)
char_list = None
span_list = []
mupdf.fz_clear_buffer(buff)
span_rect = mupdf.FzRect(mupdf.FzRect.Fixed_EMPTY)
line_rect = mupdf.FzRect(mupdf.FzRect.Fixed_EMPTY)
class char_style:
def __init__(self, rhs=None):
if rhs:
self.size = rhs.size
self.flags = rhs.flags
self.font = rhs.font
self.color = rhs.color
self.asc = rhs.asc
self.desc = rhs.desc
else:
self.size = -1
self.flags = -1
self.font = ''
self.color = -1
self.asc = 0
self.desc = 0
def __str__(self):
return f'{self.size} {self.flags} {self.font} {self.color} {self.asc} {self.desc}'
old_style = char_style()
style = char_style()
span = None
span_origin = None
for ch in line:
# start-trace
r = JM_char_bbox(line, ch)
if (not JM_rects_overlap(tp_rect, r)
and not mupdf.fz_is_infinite_rect(tp_rect)
):
continue
flags = JM_char_font_flags(mupdf.FzFont(mupdf.ll_fz_keep_font(ch.m_internal.font)), line, ch)
origin = mupdf.FzPoint(ch.m_internal.origin)
style.size = ch.m_internal.size
style.flags = flags
style.font = JM_font_name(mupdf.FzFont(mupdf.ll_fz_keep_font(ch.m_internal.font)))
style.color = ch.m_internal.color
style.asc = JM_font_ascender(mupdf.FzFont(mupdf.ll_fz_keep_font(ch.m_internal.font)))
style.desc = JM_font_descender(mupdf.FzFont(mupdf.ll_fz_keep_font(ch.m_internal.font)))
if (style.size != old_style.size
or style.flags != old_style.flags
or style.color != old_style.color
or style.font != old_style.font
):
if old_style.size >= 0:
# not first one, output previous
if raw:
# put character list in the span
span[dictkey_chars] = char_list
char_list = None
else:
# put text string in the span
span[dictkey_text] = JM_EscapeStrFromBuffer( buff)
mupdf.fz_clear_buffer(buff)
span[dictkey_origin] = JM_py_from_point(span_origin)
span[dictkey_bbox] = JM_py_from_rect(span_rect)
line_rect = mupdf.fz_union_rect(line_rect, span_rect)
span_list.append( span)
span = None
span = dict()
asc = style.asc
desc = style.desc
if style.asc < 1e-3:
asc = 0.9
desc = -0.1
span[dictkey_size] = style.size
span[dictkey_flags] = style.flags
span[dictkey_font] = JM_EscapeStrFromStr(style.font)
span[dictkey_color] = style.color
span["ascender"] = asc
span["descender"] = desc
# Need to be careful here - doing 'old_style=style' does a shallow
# copy, but we need to keep old_style as a distinct instance.
old_style = char_style(style)
span_rect = r
span_origin = origin
span_rect = mupdf.fz_union_rect(span_rect, r)
if raw: # make and append a char dict
char_dict = dict()
char_dict[dictkey_origin] = JM_py_from_point( ch.m_internal.origin)
char_dict[dictkey_bbox] = JM_py_from_rect(r)
char_dict[dictkey_c] = chr(ch.m_internal.c)
if char_list is None:
char_list = []
char_list.append(char_dict)
else: # add character byte to buffer
JM_append_rune(buff, ch.m_internal.c)
# all characters processed, now flush remaining span
if span:
if raw:
span[dictkey_chars] = char_list
char_list = None
else:
span[dictkey_text] = JM_EscapeStrFromBuffer(buff)
mupdf.fz_clear_buffer(buff)
span[dictkey_origin] = JM_py_from_point(span_origin)
span[dictkey_bbox] = JM_py_from_rect(span_rect)
if not mupdf.fz_is_empty_rect(span_rect):
span_list.append(span)
line_rect = mupdf.fz_union_rect(line_rect, span_rect)
span = None
if not mupdf.fz_is_empty_rect(line_rect):
line_dict[dictkey_spans] = span_list
else:
line_dict[dictkey_spans] = span_list
return line_rect
def JM_make_image_block(block, block_dict):
image = block.i_image()
n = mupdf.fz_colorspace_n(image.colorspace())
w = image.w()
h = image.h()
type_ = mupdf.FZ_IMAGE_UNKNOWN
# fz_compressed_image_buffer() is not available because
# `fz_compressed_buffer` is not copyable.
ll_fz_compressed_buffer = mupdf.ll_fz_compressed_image_buffer(image.m_internal)
if ll_fz_compressed_buffer:
type_ = ll_fz_compressed_buffer.params.type
if type_ < mupdf.FZ_IMAGE_BMP or type_ == mupdf.FZ_IMAGE_JBIG2:
type_ = mupdf.FZ_IMAGE_UNKNOWN
bytes_ = None
if ll_fz_compressed_buffer and type_ != mupdf.FZ_IMAGE_UNKNOWN:
buf = mupdf.FzBuffer( mupdf.ll_fz_keep_buffer( ll_fz_compressed_buffer.buffer))
ext = JM_image_extension(type_)
else:
buf = mupdf.fz_new_buffer_from_image_as_png(image, mupdf.FzColorParams())
ext = "png"
bytes_ = JM_BinFromBuffer(buf)
block_dict[ dictkey_width] = w
block_dict[ dictkey_height] = h
block_dict[ dictkey_ext] = ext
block_dict[ dictkey_colorspace] = n
block_dict[ dictkey_xres] = image.xres()
block_dict[ dictkey_yres] = image.yres()
block_dict[ dictkey_bpc] = image.bpc()
block_dict[ dictkey_matrix] = JM_py_from_matrix(block.i_transform())
block_dict[ dictkey_size] = len(bytes_)
block_dict[ dictkey_image] = bytes_
def JM_make_text_block(block, block_dict, raw, buff, tp_rect):
if g_use_extra:
return extra.JM_make_text_block(block.m_internal, block_dict, raw, buff.m_internal, tp_rect.m_internal)
line_list = []
block_rect = mupdf.FzRect(mupdf.FzRect.Fixed_EMPTY)
#log(f'{block=}')
for line in block:
#log(f'{line=}')
if (mupdf.fz_is_empty_rect(mupdf.fz_intersect_rect(tp_rect, mupdf.FzRect(line.m_internal.bbox)))
and not mupdf.fz_is_infinite_rect(tp_rect)
):
continue
line_dict = dict()
line_rect = JM_make_spanlist(line_dict, line, raw, buff, tp_rect)
block_rect = mupdf.fz_union_rect(block_rect, line_rect)
line_dict[dictkey_wmode] = line.m_internal.wmode
line_dict[dictkey_dir] = JM_py_from_point(line.m_internal.dir)
line_dict[dictkey_bbox] = JM_py_from_rect(line_rect)
line_list.append(line_dict)
block_dict[dictkey_bbox] = JM_py_from_rect(block_rect)
block_dict[dictkey_lines] = line_list
def JM_make_textpage_dict(tp, page_dict, raw):
if g_use_extra:
return extra.JM_make_textpage_dict(tp.m_internal, page_dict, raw)
text_buffer = mupdf.fz_new_buffer(128)
block_list = []
tp_rect = mupdf.FzRect(tp.m_internal.mediabox)
block_n = -1
#log( 'JM_make_textpage_dict {=tp}')
for block in tp:
block_n += 1
if (not mupdf.fz_contains_rect(tp_rect, mupdf.FzRect(block.m_internal.bbox))
and not mupdf.fz_is_infinite_rect(tp_rect)
and block.m_internal.type == mupdf.FZ_STEXT_BLOCK_IMAGE
):
continue
if (not mupdf.fz_is_infinite_rect(tp_rect)
and mupdf.fz_is_empty_rect(mupdf.fz_intersect_rect(tp_rect, mupdf.FzRect(block.m_internal.bbox)))
):
continue
block_dict = dict()
block_dict[dictkey_number] = block_n
block_dict[dictkey_type] = block.m_internal.type
if block.m_internal.type == mupdf.FZ_STEXT_BLOCK_IMAGE:
block_dict[dictkey_bbox] = JM_py_from_rect(block.m_internal.bbox)
JM_make_image_block(block, block_dict)
else:
JM_make_text_block(block, block_dict, raw, text_buffer, tp_rect)
block_list.append(block_dict)
page_dict[dictkey_blocks] = block_list
def JM_matrix_from_py(m):
a = [0, 0, 0, 0, 0, 0]
if isinstance(m, mupdf.FzMatrix):
return m
if isinstance(m, Matrix):
return mupdf.FzMatrix(m.a, m.b, m.c, m.d, m.e, m.f)
if not m or not PySequence_Check(m) or PySequence_Size(m) != 6:
return mupdf.FzMatrix()
for i in range(6):
a[i] = JM_FLOAT_ITEM(m, i)
if a[i] is None:
return mupdf.FzRect()
return mupdf.FzMatrix(a[0], a[1], a[2], a[3], a[4], a[5])
def JM_mediabox(page_obj):
'''
return a PDF page's MediaBox
'''
page_mediabox = mupdf.FzRect(mupdf.FzRect.Fixed_UNIT)
mediabox = mupdf.pdf_to_rect(
mupdf.pdf_dict_get_inheritable(page_obj, PDF_NAME('MediaBox'))
)
if mupdf.fz_is_empty_rect(mediabox) or mupdf.fz_is_infinite_rect(mediabox):
mediabox.x0 = 0
mediabox.y0 = 0
mediabox.x1 = 612
mediabox.y1 = 792
page_mediabox = mupdf.FzRect(
mupdf.fz_min(mediabox.x0, mediabox.x1),
mupdf.fz_min(mediabox.y0, mediabox.y1),
mupdf.fz_max(mediabox.x0, mediabox.x1),
mupdf.fz_max(mediabox.y0, mediabox.y1),
)
if (page_mediabox.x1 - page_mediabox.x0 < 1
or page_mediabox.y1 - page_mediabox.y0 < 1
):
page_mediabox = mupdf.FzRect(mupdf.FzRect.Fixed_UNIT)
return page_mediabox
def JM_merge_range(
doc_des,
doc_src,
spage,
epage,
apage,
rotate,
links,
annots,
show_progress,
graft_map,
):
'''
Copy a range of pages (spage, epage) from a source PDF to a specified
location (apage) of the target PDF.
If spage > epage, the sequence of source pages is reversed.
'''
if g_use_extra:
return extra.JM_merge_range(
doc_des,
doc_src,
spage,
epage,
apage,
rotate,
links,
annots,
show_progress,
graft_map,
)
afterpage = apage
counter = 0 # copied pages counter
total = mupdf.fz_absi(epage - spage) + 1 # total pages to copy
if spage < epage:
page = spage
while page <= epage:
page_merge(doc_des, doc_src, page, afterpage, rotate, links, annots, graft_map)
counter += 1
if show_progress > 0 and counter % show_progress == 0:
message(f"Inserted {counter} of {total} pages.")
page += 1
afterpage += 1
else:
page = spage
while page >= epage:
page_merge(doc_des, doc_src, page, afterpage, rotate, links, annots, graft_map)
counter += 1
if show_progress > 0 and counter % show_progress == 0:
message(f"Inserted {counter} of {total} pages.")
page -= 1
afterpage += 1
def JM_merge_resources( page, temp_res):
'''
Merge the /Resources object created by a text pdf device into the page.
The device may have created multiple /ExtGState/Alp? and /Font/F? objects.
These need to be renamed (renumbered) to not overwrite existing page
objects from previous executions.
Returns the next available numbers n, m for objects /Alp<n>, /F<m>.
'''
# page objects /Resources, /Resources/ExtGState, /Resources/Font
resources = mupdf.pdf_dict_get(page.obj(), PDF_NAME('Resources'))
main_extg = mupdf.pdf_dict_get(resources, PDF_NAME('ExtGState'))
main_fonts = mupdf.pdf_dict_get(resources, PDF_NAME('Font'))
# text pdf device objects /ExtGState, /Font
temp_extg = mupdf.pdf_dict_get(temp_res, PDF_NAME('ExtGState'))
temp_fonts = mupdf.pdf_dict_get(temp_res, PDF_NAME('Font'))
max_alp = -1
max_fonts = -1
# Handle /Alp objects
if mupdf.pdf_is_dict(temp_extg): # any created at all?
n = mupdf.pdf_dict_len(temp_extg)
if mupdf.pdf_is_dict(main_extg): # does page have /ExtGState yet?
for i in range(mupdf.pdf_dict_len(main_extg)):
# get highest number of objects named /Alpxxx
alp = mupdf.pdf_to_name( mupdf.pdf_dict_get_key(main_extg, i))
if not alp.startswith('Alp'):
continue
j = mupdf.fz_atoi(alp[3:])
if j > max_alp:
max_alp = j
else: # create a /ExtGState for the page
main_extg = mupdf.pdf_dict_put_dict(resources, PDF_NAME('ExtGState'), n)
max_alp += 1
for i in range(n): # copy over renumbered /Alp objects
alp = mupdf.pdf_to_name( mupdf.pdf_dict_get_key( temp_extg, i))
j = mupdf.fz_atoi(alp[3:]) + max_alp
text = f'Alp{j}'
val = mupdf.pdf_dict_get_val( temp_extg, i)
mupdf.pdf_dict_puts(main_extg, text, val)
if mupdf.pdf_is_dict(main_fonts): # has page any fonts yet?
for i in range(mupdf.pdf_dict_len(main_fonts)): # get max font number
font = mupdf.pdf_to_name( mupdf.pdf_dict_get_key( main_fonts, i))
if not font.startswith("F"):
continue
j = mupdf.fz_atoi(font[1:])
if j > max_fonts:
max_fonts = j
else: # create a Resources/Font for the page
main_fonts = mupdf.pdf_dict_put_dict(resources, PDF_NAME('Font'), 2)
max_fonts += 1
for i in range(mupdf.pdf_dict_len(temp_fonts)): # copy renumbered fonts
font = mupdf.pdf_to_name( mupdf.pdf_dict_get_key( temp_fonts, i))
j = mupdf.fz_atoi(font[1:]) + max_fonts
text = f'F{j}'
val = mupdf.pdf_dict_get_val(temp_fonts, i)
mupdf.pdf_dict_puts(main_fonts, text, val)
return (max_alp, max_fonts) # next available numbers
def JM_mupdf_warning( text):
'''
redirect MuPDF warnings
'''
JM_mupdf_warnings_store.append(text)
if JM_mupdf_show_warnings:
message(f'MuPDF warning: {text}')
def JM_mupdf_error( text):
JM_mupdf_warnings_store.append(text)
if JM_mupdf_show_errors:
message(f'MuPDF error: {text}\n')
def JM_new_bbox_device(rc, inc_layers):
assert isinstance(rc, list)
return JM_new_bbox_device_Device( rc, inc_layers)
def JM_new_buffer_from_stext_page(page):
'''
make a buffer from an stext_page's text
'''
assert isinstance(page, mupdf.FzStextPage)
rect = mupdf.FzRect(page.m_internal.mediabox)
buf = mupdf.fz_new_buffer(256)
for block in page:
if block.m_internal.type == mupdf.FZ_STEXT_BLOCK_TEXT:
for line in block:
for ch in line:
if (not JM_rects_overlap(rect, JM_char_bbox(line, ch))
and not mupdf.fz_is_infinite_rect(rect)
):
continue
mupdf.fz_append_rune(buf, ch.m_internal.c)
mupdf.fz_append_byte(buf, ord('\n'))
mupdf.fz_append_byte(buf, ord('\n'))
return buf
def JM_new_javascript(pdf, value):
'''
make new PDF action object from JavaScript source
Parameters are a PDF document and a Python string.
Returns a PDF action object.
'''
if value is None:
# no argument given
return
data = JM_StrAsChar(value)
if data is None:
# not convertible to char*
return
res = mupdf.fz_new_buffer_from_copied_data(data.encode('utf8'))
source = mupdf.pdf_add_stream(pdf, res, mupdf.PdfObj(), 0)
newaction = mupdf.pdf_add_new_dict(pdf, 4)
mupdf.pdf_dict_put(newaction, PDF_NAME('S'), mupdf.pdf_new_name('JavaScript'))
mupdf.pdf_dict_put(newaction, PDF_NAME('JS'), source)
return newaction
def JM_new_output_fileptr(bio):
return JM_new_output_fileptr_Output( bio)
def JM_norm_rotation(rotate):
'''
# return normalized /Rotate value:one of 0, 90, 180, 270
'''
while rotate < 0:
rotate += 360
while rotate >= 360:
rotate -= 360
if rotate % 90 != 0:
return 0
return rotate
def JM_object_to_buffer(what, compress, ascii):
res = mupdf.fz_new_buffer(512)
out = mupdf.FzOutput(res)
mupdf.pdf_print_obj(out, what, compress, ascii)
out.fz_close_output()
mupdf.fz_terminate_buffer(res)
return res
def JM_outline_xrefs(obj, xrefs):
'''
Return list of outline xref numbers. Recursive function. Arguments:
'obj' first OL item
'xrefs' empty Python list
'''
if not obj.m_internal:
return xrefs
thisobj = obj
while thisobj.m_internal:
newxref = mupdf.pdf_to_num( thisobj)
if newxref in xrefs or mupdf.pdf_dict_get( thisobj, PDF_NAME('Type')).m_internal:
# circular ref or top of chain: terminate
break
xrefs.append( newxref)
first = mupdf.pdf_dict_get( thisobj, PDF_NAME('First')) # try go down
if mupdf.pdf_is_dict( first):
xrefs = JM_outline_xrefs( first, xrefs)
thisobj = mupdf.pdf_dict_get( thisobj, PDF_NAME('Next')) # try go next
parent = mupdf.pdf_dict_get( thisobj, PDF_NAME('Parent')) # get parent
if not mupdf.pdf_is_dict( thisobj):
thisobj = parent
return xrefs
def JM_page_rotation(page):
'''
return a PDF page's /Rotate value: one of (0, 90, 180, 270)
'''
rotate = 0
obj = mupdf.pdf_dict_get_inheritable( page.obj(), mupdf.PDF_ENUM_NAME_Rotate)
rotate = mupdf.pdf_to_int(obj)
rotate = JM_norm_rotation(rotate)
return rotate
def JM_pdf_obj_from_str(doc, src):
'''
create PDF object from given string (new in v1.14.0: MuPDF dropped it)
'''
# fixme: seems inefficient to convert to bytes instance then make another
# copy inside fz_new_buffer_from_copied_data(), but no other way?
#
buffer_ = mupdf.fz_new_buffer_from_copied_data(bytes(src, 'utf8'))
stream = mupdf.fz_open_buffer(buffer_)
lexbuf = mupdf.PdfLexbuf(mupdf.PDF_LEXBUF_SMALL)
result = mupdf.pdf_parse_stm_obj(doc, stream, lexbuf)
return result
def JM_pixmap_from_display_list(
list_,
ctm,
cs,
alpha,
clip,
seps,
):
'''
Version of fz_new_pixmap_from_display_list (util.c) to also support
rendering of only the 'clip' part of the displaylist rectangle
'''
assert isinstance(list_, mupdf.FzDisplayList)
if seps is None:
seps = mupdf.FzSeparations()
assert seps is None or isinstance(seps, mupdf.FzSeparations), f'{type(seps)=}: {seps}'
rect = mupdf.fz_bound_display_list(list_)
matrix = JM_matrix_from_py(ctm)
rclip = JM_rect_from_py(clip)
rect = mupdf.fz_intersect_rect(rect, rclip) # no-op if clip is not given
rect = mupdf.fz_transform_rect(rect, matrix)
irect = mupdf.fz_round_rect(rect)
assert isinstance( cs, mupdf.FzColorspace)
pix = mupdf.fz_new_pixmap_with_bbox(cs, irect, seps, alpha)
if alpha:
mupdf.fz_clear_pixmap(pix)
else:
mupdf.fz_clear_pixmap_with_value(pix, 0xFF)
if not mupdf.fz_is_infinite_rect(rclip):
dev = mupdf.fz_new_draw_device_with_bbox(matrix, pix, irect)
mupdf.fz_run_display_list(list_, dev, mupdf.FzMatrix(), rclip, mupdf.FzCookie())
else:
dev = mupdf.fz_new_draw_device(matrix, pix)
mupdf.fz_run_display_list(list_, dev, mupdf.FzMatrix(), mupdf.FzRect(mupdf.FzRect.Fixed_INFINITE), mupdf.FzCookie())
mupdf.fz_close_device(dev)
# Use special raw Pixmap constructor so we don't set alpha to true.
return Pixmap( 'raw', pix)
def JM_point_from_py(p):
'''
PySequence to fz_point. Default: (FZ_MIN_INF_RECT, FZ_MIN_INF_RECT)
'''
if isinstance(p, mupdf.FzPoint):
return p
if isinstance(p, Point):
return mupdf.FzPoint(p.x, p.y)
if g_use_extra:
return extra.JM_point_from_py( p)
p0 = mupdf.FzPoint(0, 0)
x = JM_FLOAT_ITEM(p, 0)
y = JM_FLOAT_ITEM(p, 1)
if x is None or y is None:
return p0
x = max( x, FZ_MIN_INF_RECT)
y = max( y, FZ_MIN_INF_RECT)
x = min( x, FZ_MAX_INF_RECT)
y = min( y, FZ_MAX_INF_RECT)
return mupdf.FzPoint(x, y)
def JM_print_stext_page_as_text(res, page):
'''
Plain text output. An identical copy of fz_print_stext_page_as_text,
but lines within a block are concatenated by space instead a new-line
character (which else leads to 2 new-lines).
'''
if 1 and g_use_extra:
return extra.JM_print_stext_page_as_text(res, page)
assert isinstance(res, mupdf.FzBuffer)
assert isinstance(page, mupdf.FzStextPage)
rect = mupdf.FzRect(page.m_internal.mediabox)
last_char = 0
n_blocks = 0
n_lines = 0
n_chars = 0
for n_blocks2, block in enumerate( page):
if block.m_internal.type == mupdf.FZ_STEXT_BLOCK_TEXT:
for n_lines2, line in enumerate( block):
for n_chars2, ch in enumerate( line):
pass
n_chars += n_chars2
n_lines += n_lines2
n_blocks += n_blocks2
for block in page:
if block.m_internal.type == mupdf.FZ_STEXT_BLOCK_TEXT:
for line in block:
last_char = 0
for ch in line:
chbbox = JM_char_bbox(line, ch)
if (mupdf.fz_is_infinite_rect(rect)
or JM_rects_overlap(rect, chbbox)
):
#raw += chr(ch.m_internal.c)
last_char = ch.m_internal.c
#log( '{=last_char!r utf!r}')
JM_append_rune(res, last_char)
if last_char != 10 and last_char > 0:
mupdf.fz_append_string(res, "\n")
def JM_put_script(annot_obj, key1, key2, value):
'''
Create a JavaScript PDF action.
Usable for all object types which support PDF actions, even if the
argument name suggests annotations. Up to 2 key values can be specified, so
JavaScript actions can be stored for '/A' and '/AA/?' keys.
'''
key1_obj = mupdf.pdf_dict_get(annot_obj, key1)
pdf = mupdf.pdf_get_bound_document(annot_obj) # owning PDF
# if no new script given, just delete corresponding key
if not value:
if key2 is None or not key2.m_internal:
mupdf.pdf_dict_del(annot_obj, key1)
elif key1_obj.m_internal:
mupdf.pdf_dict_del(key1_obj, key2)
return
# read any existing script as a PyUnicode string
if not key2.m_internal or not key1_obj.m_internal:
script = JM_get_script(key1_obj)
else:
script = JM_get_script(mupdf.pdf_dict_get(key1_obj, key2))
# replace old script, if different from new one
if value != script:
newaction = JM_new_javascript(pdf, value)
if not key2.m_internal:
mupdf.pdf_dict_put(annot_obj, key1, newaction)
else:
mupdf.pdf_dict_putl(annot_obj, newaction, key1, key2)
def JM_py_from_irect(r):
return r.x0, r.y0, r.x1, r.y1
def JM_py_from_matrix(m):
return m.a, m.b, m.c, m.d, m.e, m.f
def JM_py_from_point(p):
return p.x, p.y
def JM_py_from_quad(q):
'''
PySequence from fz_quad.
'''
return (
(q.ul.x, q.ul.y),
(q.ur.x, q.ur.y),
(q.ll.x, q.ll.y),
(q.lr.x, q.lr.y),
)
def JM_py_from_rect(r):
return r.x0, r.y0, r.x1, r.y1
def JM_quad_from_py(r):
if isinstance(r, mupdf.FzQuad):
return r
# cover all cases of 4-float-sequences
if hasattr(r, "__getitem__") and len(r) == 4 and hasattr(r[0], "__float__"):
r = mupdf.FzRect(*tuple(r))
if isinstance( r, mupdf.FzRect):
return mupdf.fz_quad_from_rect( r)
if isinstance( r, Quad):
return mupdf.fz_make_quad(
r.ul.x, r.ul.y,
r.ur.x, r.ur.y,
r.ll.x, r.ll.y,
r.lr.x, r.lr.y,
)
q = mupdf.fz_make_quad(0, 0, 0, 0, 0, 0, 0, 0)
p = [0,0,0,0]
if not r or not isinstance(r, (tuple, list)) or len(r) != 4:
return q
if JM_FLOAT_ITEM(r, 0) is None:
return mupdf.fz_quad_from_rect(JM_rect_from_py(r))
for i in range(4):
if i >= len(r):
return q # invalid: cancel the rest
obj = r[i] # next point item
if not PySequence_Check(obj) or PySequence_Size(obj) != 2:
return q # invalid: cancel the rest
p[i].x = JM_FLOAT_ITEM(obj, 0)
p[i].y = JM_FLOAT_ITEM(obj, 1)
if p[i].x is None or p[i].y is None:
return q
p[i].x = max( p[i].x, FZ_MIN_INF_RECT)
p[i].y = max( p[i].y, FZ_MIN_INF_RECT)
p[i].x = min( p[i].x, FZ_MAX_INF_RECT)
p[i].y = min( p[i].y, FZ_MAX_INF_RECT)
q.ul = p[0]
q.ur = p[1]
q.ll = p[2]
q.lr = p[3]
return q
def JM_read_contents(pageref):
'''
Read and concatenate a PDF page's /Contents object(s) in a buffer
'''
assert isinstance(pageref, mupdf.PdfObj), f'{type(pageref)}'
contents = mupdf.pdf_dict_get(pageref, mupdf.PDF_ENUM_NAME_Contents)
if mupdf.pdf_is_array(contents):
res = mupdf.FzBuffer(1024)
for i in range(mupdf.pdf_array_len(contents)):
if i > 0:
mupdf.fz_append_byte(res, 32)
obj = mupdf.pdf_array_get(contents, i)
if mupdf.pdf_is_stream(obj):
nres = mupdf.pdf_load_stream(obj)
mupdf.fz_append_buffer(res, nres)
elif contents.m_internal:
res = mupdf.pdf_load_stream(contents)
else:
res = b""
return res
def JM_rect_from_py(r):
if isinstance(r, mupdf.FzRect):
return r
if isinstance(r, mupdf.FzIrect):
return mupdf.FzRect(r)
if isinstance(r, Rect):
return mupdf.fz_make_rect(r.x0, r.y0, r.x1, r.y1)
if isinstance(r, IRect):
return mupdf.fz_make_rect(r.x0, r.y0, r.x1, r.y1)
if not r or not PySequence_Check(r) or PySequence_Size(r) != 4:
return mupdf.FzRect(mupdf.FzRect.Fixed_INFINITE)
f = [0, 0, 0, 0]
for i in range(4):
f[i] = JM_FLOAT_ITEM(r, i)
if f[i] is None:
return mupdf.FzRect(mupdf.FzRect.Fixed_INFINITE)
if f[i] < FZ_MIN_INF_RECT:
f[i] = FZ_MIN_INF_RECT
if f[i] > FZ_MAX_INF_RECT:
f[i] = FZ_MAX_INF_RECT
return mupdf.fz_make_rect(f[0], f[1], f[2], f[3])
def JM_rects_overlap(a, b):
if (0
or a.x0 >= b.x1
or a.y0 >= b.y1
or a.x1 <= b.x0
or a.y1 <= b.y0
):
return 0
return 1
def JM_refresh_links( page):
'''
refreshes the link and annotation tables of a page
'''
if page is None or not page.m_internal:
return
obj = mupdf.pdf_dict_get( page.obj(), PDF_NAME('Annots'))
if obj.m_internal:
pdf = page.doc()
number = mupdf.pdf_lookup_page_number( pdf, page.obj())
page_mediabox = mupdf.FzRect()
page_ctm = mupdf.FzMatrix()
mupdf.pdf_page_transform( page, page_mediabox, page_ctm)
link = mupdf.pdf_load_link_annots( pdf, page, obj, number, page_ctm)
page.m_internal.links = mupdf.ll_fz_keep_link( link.m_internal)
def JM_rotate_page_matrix(page):
'''
calculate page rotation matrices
'''
if not page.m_internal:
return mupdf.FzMatrix() # no valid pdf page given
rotation = JM_page_rotation(page)
#log( '{rotation=}')
if rotation == 0:
return mupdf.FzMatrix() # no rotation
cb_size = JM_cropbox_size(page.obj())
w = cb_size.x
h = cb_size.y
#log( '{=h w}')
if rotation == 90:
m = mupdf.fz_make_matrix(0, 1, -1, 0, h, 0)
elif rotation == 180:
m = mupdf.fz_make_matrix(-1, 0, 0, -1, w, h)
else:
m = mupdf.fz_make_matrix(0, -1, 1, 0, 0, w)
#log( 'returning {m=}')
return m
def JM_search_stext_page(page, needle):
if g_use_extra:
return extra.JM_search_stext_page(page.m_internal, needle)
rect = mupdf.FzRect(page.m_internal.mediabox)
if not needle:
return
quads = []
class Hits:
def __str__(self):
return f'Hits(len={self.len} quads={self.quads} hfuzz={self.hfuzz} vfuzz={self.vfuzz}'
hits = Hits()
hits.len = 0
hits.quads = quads
hits.hfuzz = 0.2 # merge kerns but not large gaps
hits.vfuzz = 0.1
buffer_ = JM_new_buffer_from_stext_page(page)
haystack_string = mupdf.fz_string_from_buffer(buffer_)
haystack = 0
begin, end = find_string(haystack_string[haystack:], needle)
if begin is None:
#goto no_more_matches;
return quads
begin += haystack
end += haystack
inside = 0
i = 0
for block in page:
if block.m_internal.type != mupdf.FZ_STEXT_BLOCK_TEXT:
continue
for line in block:
for ch in line:
i += 1
if not mupdf.fz_is_infinite_rect(rect):
r = JM_char_bbox(line, ch)
if not JM_rects_overlap(rect, r):
#goto next_char;
continue
while 1:
#try_new_match:
if not inside:
if haystack >= begin:
inside = 1
if inside:
if haystack < end:
on_highlight_char(hits, line, ch)
break
else:
inside = 0
begin, end = find_string(haystack_string[haystack:], needle)
if begin is None:
#goto no_more_matches;
return quads
else:
#goto try_new_match;
begin += haystack
end += haystack
continue
break
haystack += 1
#next_char:;
assert haystack_string[haystack] == '\n', \
f'{haystack=} {haystack_string[haystack]=}'
haystack += 1
assert haystack_string[haystack] == '\n', \
f'{haystack=} {haystack_string[haystack]=}'
haystack += 1
#no_more_matches:;
return quads
def JM_scan_resources(pdf, rsrc, liste, what, stream_xref, tracer):
'''
Step through /Resources, looking up image, xobject or font information
'''
if mupdf.pdf_mark_obj(rsrc):
mupdf.fz_warn('Circular dependencies! Consider page cleaning.')
return # Circular dependencies!
try:
xobj = mupdf.pdf_dict_get(rsrc, mupdf.PDF_ENUM_NAME_XObject)
if what == 1: # lookup fonts
font = mupdf.pdf_dict_get(rsrc, mupdf.PDF_ENUM_NAME_Font)
JM_gather_fonts(pdf, font, liste, stream_xref)
elif what == 2: # look up images
JM_gather_images(pdf, xobj, liste, stream_xref)
elif what == 3: # look up form xobjects
JM_gather_forms(pdf, xobj, liste, stream_xref)
else: # should never happen
return
# check if we need to recurse into Form XObjects
n = mupdf.pdf_dict_len(xobj)
for i in range(n):
obj = mupdf.pdf_dict_get_val(xobj, i)
if mupdf.pdf_is_stream(obj):
sxref = mupdf.pdf_to_num(obj)
else:
sxref = 0
subrsrc = mupdf.pdf_dict_get(obj, mupdf.PDF_ENUM_NAME_Resources)
if subrsrc.m_internal:
sxref_t = sxref
if sxref_t not in tracer:
tracer.append(sxref_t)
JM_scan_resources( pdf, subrsrc, liste, what, sxref, tracer)
else:
mupdf.fz_warn('Circular dependencies! Consider page cleaning.')
return
finally:
mupdf.pdf_unmark_obj(rsrc)
def JM_set_choice_options(annot, liste):
'''
set ListBox / ComboBox values
'''
if not liste:
return
assert isinstance( liste, (tuple, list))
n = len( liste)
if n == 0:
return
annot_obj = mupdf.pdf_annot_obj( annot)
pdf = mupdf.pdf_get_bound_document( annot_obj)
optarr = mupdf.pdf_new_array( pdf, n)
for i in range(n):
val = liste[i]
opt = val
if isinstance(opt, str):
mupdf.pdf_array_push_text_string( optarr, opt)
else:
assert isinstance( val, (tuple, list)) and len( val) == 2, 'bad choice field list'
opt1, opt2 = val
assert opt1 and opt2, 'bad choice field list'
optarrsub = mupdf.pdf_array_push_array( optarr, 2)
mupdf.pdf_array_push_text_string( optarrsub, opt1)
mupdf.pdf_array_push_text_string( optarrsub, opt2)
mupdf.pdf_dict_put( annot_obj, PDF_NAME('Opt'), optarr)
def JM_set_field_type(doc, obj, type):
'''
Set the field type
'''
setbits = 0
clearbits = 0
typename = None
if type == mupdf.PDF_WIDGET_TYPE_BUTTON:
typename = PDF_NAME('Btn')
setbits = mupdf.PDF_BTN_FIELD_IS_PUSHBUTTON
elif type == mupdf.PDF_WIDGET_TYPE_RADIOBUTTON:
typename = PDF_NAME('Btn')
clearbits = mupdf.PDF_BTN_FIELD_IS_PUSHBUTTON
setbits = mupdf.PDF_BTN_FIELD_IS_RADIO
elif type == mupdf.PDF_WIDGET_TYPE_CHECKBOX:
typename = PDF_NAME('Btn')
clearbits = (mupdf.PDF_BTN_FIELD_IS_PUSHBUTTON | mupdf.PDF_BTN_FIELD_IS_RADIO)
elif type == mupdf.PDF_WIDGET_TYPE_TEXT:
typename = PDF_NAME('Tx')
elif type == mupdf.PDF_WIDGET_TYPE_LISTBOX:
typename = PDF_NAME('Ch')
clearbits = mupdf.PDF_CH_FIELD_IS_COMBO
elif type == mupdf.PDF_WIDGET_TYPE_COMBOBOX:
typename = PDF_NAME('Ch')
setbits = mupdf.PDF_CH_FIELD_IS_COMBO
elif type == mupdf.PDF_WIDGET_TYPE_SIGNATURE:
typename = PDF_NAME('Sig')
if typename is not None and typename.m_internal:
mupdf.pdf_dict_put(obj, PDF_NAME('FT'), typename)
if setbits != 0 or clearbits != 0:
bits = mupdf.pdf_dict_get_int(obj, PDF_NAME('Ff'))
bits &= ~clearbits
bits |= setbits
mupdf.pdf_dict_put_int(obj, PDF_NAME('Ff'), bits)
def JM_set_object_value(obj, key, value):
'''
Set a PDF dict key to some value
'''
eyecatcher = "fitz: replace me!"
pdf = mupdf.pdf_get_bound_document(obj)
# split PDF key at path seps and take last key part
list_ = key.split('/')
len_ = len(list_)
i = len_ - 1
skey = list_[i]
del list_[i] # del the last sub-key
len_ = len(list_) # remaining length
testkey = mupdf.pdf_dict_getp(obj, key) # check if key already exists
if not testkey.m_internal:
#No, it will be created here. But we cannot allow this happening if
#indirect objects are referenced. So we check all higher level
#sub-paths for indirect references.
while len_ > 0:
t = '/'.join(list_) # next high level
if mupdf.pdf_is_indirect(mupdf.pdf_dict_getp(obj, JM_StrAsChar(t))):
raise Exception("path to '%s' has indirects", JM_StrAsChar(skey))
del list_[len_ - 1] # del last sub-key
len_ = len(list_) # remaining length
# Insert our eyecatcher. Will create all sub-paths in the chain, or
# respectively remove old value of key-path.
mupdf.pdf_dict_putp(obj, key, mupdf.pdf_new_text_string(eyecatcher))
testkey = mupdf.pdf_dict_getp(obj, key)
if not mupdf.pdf_is_string(testkey):
raise Exception("cannot insert value for '%s'", key)
temp = mupdf.pdf_to_text_string(testkey)
if temp != eyecatcher:
raise Exception("cannot insert value for '%s'", key)
# read the result as a string
res = JM_object_to_buffer(obj, 1, 0)
objstr = JM_EscapeStrFromBuffer(res)
# replace 'eyecatcher' by desired 'value'
nullval = "/%s(%s)" % ( skey, eyecatcher)
newval = "/%s %s" % (skey, value)
newstr = objstr.replace(nullval, newval, 1)
# make PDF object from resulting string
new_obj = JM_pdf_obj_from_str(pdf, newstr)
return new_obj
def JM_set_ocg_arrays(conf, basestate, on, off, rbgroups, locked):
if basestate:
mupdf.pdf_dict_put_name( conf, PDF_NAME('BaseState'), basestate)
if on is not None:
mupdf.pdf_dict_del( conf, PDF_NAME('ON'))
if on:
arr = mupdf.pdf_dict_put_array( conf, PDF_NAME('ON'), 1)
JM_set_ocg_arrays_imp( arr, on)
if off is not None:
mupdf.pdf_dict_del( conf, PDF_NAME('OFF'))
if off:
arr = mupdf.pdf_dict_put_array( conf, PDF_NAME('OFF'), 1)
JM_set_ocg_arrays_imp( arr, off)
if locked is not None:
mupdf.pdf_dict_del( conf, PDF_NAME('Locked'))
if locked:
arr = mupdf.pdf_dict_put_array( conf, PDF_NAME('Locked'), 1)
JM_set_ocg_arrays_imp( arr, locked)
if rbgroups is not None:
mupdf.pdf_dict_del( conf, PDF_NAME('RBGroups'))
if rbgroups:
arr = mupdf.pdf_dict_put_array( conf, PDF_NAME('RBGroups'), 1)
n =len(rbgroups)
for i in range(n):
item0 = rbgroups[i]
obj = mupdf.pdf_array_push_array( arr, 1)
JM_set_ocg_arrays_imp( obj, item0)
def JM_set_ocg_arrays_imp(arr, list_):
'''
Set OCG arrays from dict of Python lists
Works with dict like {"basestate":name, "on":list, "off":list, "rbg":list}
'''
pdf = mupdf.pdf_get_bound_document(arr)
for xref in list_:
obj = mupdf.pdf_new_indirect(pdf, xref, 0)
mupdf.pdf_array_push(arr, obj)
def JM_set_resource_property(ref, name, xref):
'''
Insert an item into Resources/Properties (used for Marked Content)
Arguments:
(1) e.g. page object, Form XObject
(2) marked content name
(3) xref of the referenced object (insert as indirect reference)
'''
pdf = mupdf.pdf_get_bound_document(ref)
ind = mupdf.pdf_new_indirect(pdf, xref, 0)
if not ind.m_internal:
RAISEPY(MSG_BAD_XREF, PyExc_ValueError)
resources = mupdf.pdf_dict_get(ref, PDF_NAME('Resources'))
if not resources.m_internal:
resources = mupdf.pdf_dict_put_dict(ref, PDF_NAME('Resources'), 1)
properties = mupdf.pdf_dict_get(resources, PDF_NAME('Properties'))
if not properties.m_internal:
properties = mupdf.pdf_dict_put_dict(resources, PDF_NAME('Properties'), 1)
mupdf.pdf_dict_put(properties, mupdf.pdf_new_name(name), ind)
def JM_set_widget_properties(annot, Widget):
'''
Update the PDF form field with the properties from a Python Widget object.
Called by "Page.add_widget" and "Annot.update_widget".
'''
if isinstance( annot, Annot):
annot = annot.this
assert isinstance( annot, mupdf.PdfAnnot), f'{type(annot)=} {type=}'
page = mupdf.pdf_annot_page(annot)
annot_obj = mupdf.pdf_annot_obj(annot)
pdf = page.doc()
def GETATTR(name):
return getattr(Widget, name, None)
value = GETATTR("field_type")
field_type = value
# rectangle --------------------------------------------------------------
value = GETATTR("rect")
rect = JM_rect_from_py(value)
rot_mat = JM_rotate_page_matrix(page)
rect = mupdf.fz_transform_rect(rect, rot_mat)
mupdf.pdf_set_annot_rect(annot, rect)
# fill color -------------------------------------------------------------
value = GETATTR("fill_color")
if value and PySequence_Check(value):
n = len(value)
fill_col = mupdf.pdf_new_array(pdf, n)
col = 0
for i in range(n):
col = value[i]
mupdf.pdf_array_push_real(fill_col, col)
mupdf.pdf_field_set_fill_color(annot_obj, fill_col)
# dashes -----------------------------------------------------------------
value = GETATTR("border_dashes")
if value and PySequence_Check(value):
n = len(value)
dashes = mupdf.pdf_new_array(pdf, n)
for i in range(n):
mupdf.pdf_array_push_int(dashes, value[i])
mupdf.pdf_dict_putl(annot_obj, dashes, PDF_NAME('BS'), PDF_NAME('D'))
# border color -----------------------------------------------------------
value = GETATTR("border_color")
if value and PySequence_Check(value):
n = len(value)
border_col = mupdf.pdf_new_array(pdf, n)
col = 0
for i in range(n):
col = value[i]
mupdf.pdf_array_push_real(border_col, col)
mupdf.pdf_dict_putl(annot_obj, border_col, PDF_NAME('MK'), PDF_NAME('BC'))
# entry ignored - may be used later
#
#int text_format = (int) PyInt_AsLong(GETATTR("text_format"));
#
# field label -----------------------------------------------------------
value = GETATTR("field_label")
if value is not None:
label = JM_StrAsChar(value)
mupdf.pdf_dict_put_text_string(annot_obj, PDF_NAME('TU'), label)
# field name -------------------------------------------------------------
value = GETATTR("field_name")
if value is not None:
name = JM_StrAsChar(value)
old_name = mupdf.pdf_load_field_name(annot_obj)
if name != old_name:
mupdf.pdf_dict_put_text_string(annot_obj, PDF_NAME('T'), name)
# max text len -----------------------------------------------------------
if field_type == mupdf.PDF_WIDGET_TYPE_TEXT:
value = GETATTR("text_maxlen")
text_maxlen = value
if text_maxlen:
mupdf.pdf_dict_put_int(annot_obj, PDF_NAME('MaxLen'), text_maxlen)
value = GETATTR("field_display")
d = value
mupdf.pdf_field_set_display(annot_obj, d)
# choice values ----------------------------------------------------------
if field_type in (mupdf.PDF_WIDGET_TYPE_LISTBOX, mupdf.PDF_WIDGET_TYPE_COMBOBOX):
value = GETATTR("choice_values")
JM_set_choice_options(annot, value)
# border style -----------------------------------------------------------
value = GETATTR("border_style")
val = JM_get_border_style(value)
mupdf.pdf_dict_putl(annot_obj, val, PDF_NAME('BS'), PDF_NAME('S'))
# border width -----------------------------------------------------------
value = GETATTR("border_width")
border_width = value
mupdf.pdf_dict_putl(
annot_obj,
mupdf.pdf_new_real(border_width),
PDF_NAME('BS'),
PDF_NAME('W'),
)
# /DA string -------------------------------------------------------------
value = GETATTR("_text_da")
da = JM_StrAsChar(value)
mupdf.pdf_dict_put_text_string(annot_obj, PDF_NAME('DA'), da)
mupdf.pdf_dict_del(annot_obj, PDF_NAME('DS')) # not supported by MuPDF
mupdf.pdf_dict_del(annot_obj, PDF_NAME('RC')) # not supported by MuPDF
# field flags ------------------------------------------------------------
field_flags = GETATTR("field_flags")
if field_flags is not None:
if field_type == mupdf.PDF_WIDGET_TYPE_COMBOBOX:
field_flags |= mupdf.PDF_CH_FIELD_IS_COMBO
elif field_type == mupdf.PDF_WIDGET_TYPE_RADIOBUTTON:
field_flags |= mupdf.PDF_BTN_FIELD_IS_RADIO
elif field_type == mupdf.PDF_WIDGET_TYPE_BUTTON:
field_flags |= mupdf.PDF_BTN_FIELD_IS_PUSHBUTTON
mupdf.pdf_dict_put_int( annot_obj, PDF_NAME('Ff'), field_flags)
# button caption ---------------------------------------------------------
value = GETATTR("button_caption")
ca = JM_StrAsChar(value)
if ca:
mupdf.pdf_field_set_button_caption(annot_obj, ca)
# script (/A) -------------------------------------------------------
value = GETATTR("script")
JM_put_script(annot_obj, PDF_NAME('A'), mupdf.PdfObj(), value)
# script (/AA/K) -------------------------------------------------------
value = GETATTR("script_stroke")
JM_put_script(annot_obj, PDF_NAME('AA'), PDF_NAME('K'), value)
# script (/AA/F) -------------------------------------------------------
value = GETATTR("script_format")
JM_put_script(annot_obj, PDF_NAME('AA'), PDF_NAME('F'), value)
# script (/AA/V) -------------------------------------------------------
value = GETATTR("script_change")
JM_put_script(annot_obj, PDF_NAME('AA'), PDF_NAME('V'), value)
# script (/AA/C) -------------------------------------------------------
value = GETATTR("script_calc")
JM_put_script(annot_obj, PDF_NAME('AA'), PDF_NAME('C'), value)
# script (/AA/Bl) -------------------------------------------------------
value = GETATTR("script_blur")
JM_put_script(annot_obj, PDF_NAME('AA'), mupdf.pdf_new_name('Bl'), value)
# script (/AA/Fo) codespell:ignore --------------------------------------
value = GETATTR("script_focus")
JM_put_script(annot_obj, PDF_NAME('AA'), mupdf.pdf_new_name('Fo'), value)
# field value ------------------------------------------------------------
value = GETATTR("field_value") # field value
text = JM_StrAsChar(value) # convert to text (may fail!)
if field_type == mupdf.PDF_WIDGET_TYPE_RADIOBUTTON:
if not value:
mupdf.pdf_set_field_value(pdf, annot_obj, "Off", 1)
mupdf.pdf_dict_put_name(annot_obj, PDF_NAME('AS'), "Off")
else:
# TODO check if another button in the group is ON and if so set it Off
onstate = mupdf.pdf_button_field_on_state(annot_obj)
if onstate.m_internal:
on = mupdf.pdf_to_name(onstate)
mupdf.pdf_set_field_value(pdf, annot_obj, on, 1)
mupdf.pdf_dict_put_name(annot_obj, PDF_NAME('AS'), on)
elif text:
mupdf.pdf_dict_put_name(annot_obj, PDF_NAME('AS'), text)
elif field_type == mupdf.PDF_WIDGET_TYPE_CHECKBOX: # will always be "Yes" or "Off"
if value is True or text == 'Yes':
onstate = mupdf.pdf_button_field_on_state(annot_obj)
on = mupdf.pdf_to_name(onstate)
mupdf.pdf_set_field_value(pdf, annot_obj, on, 1)
mupdf.pdf_dict_put_name(annot_obj, PDF_NAME('AS'), 'Yes')
mupdf.pdf_dict_put_name(annot_obj, PDF_NAME('V'), 'Yes')
else:
mupdf.pdf_dict_put_name( annot_obj, PDF_NAME('AS'), 'Off')
mupdf.pdf_dict_put_name( annot_obj, PDF_NAME('V'), 'Off')
else:
if text:
mupdf.pdf_set_field_value(pdf, annot_obj, text, 1)
if field_type in (mupdf.PDF_WIDGET_TYPE_COMBOBOX, mupdf.PDF_WIDGET_TYPE_LISTBOX):
mupdf.pdf_dict_del(annot_obj, PDF_NAME('I'))
mupdf.pdf_dirty_annot(annot)
mupdf.pdf_set_annot_hot(annot, 1)
mupdf.pdf_set_annot_active(annot, 1)
mupdf.pdf_update_annot(annot)
def JM_show_string_cs(
text,
user_font,
trm,
s,
wmode,
bidi_level,
markup_dir,
language,
):
i = 0
while i < len(s):
l, ucs = mupdf.fz_chartorune(s[i:])
i += l
gid = mupdf.fz_encode_character_sc(user_font, ucs)
if gid == 0:
gid, font = mupdf.fz_encode_character_with_fallback(user_font, ucs, 0, language)
else:
font = user_font
mupdf.fz_show_glyph(text, font, trm, gid, ucs, wmode, bidi_level, markup_dir, language)
adv = mupdf.fz_advance_glyph(font, gid, wmode)
if wmode == 0:
trm = mupdf.fz_pre_translate(trm, adv, 0)
else:
trm = mupdf.fz_pre_translate(trm, 0, -adv)
return trm
def JM_UnicodeFromBuffer(buff):
buff_bytes = mupdf.fz_buffer_extract_copy(buff)
val = buff_bytes.decode(errors='replace')
z = val.find(chr(0))
if z >= 0:
val = val[:z]
return val
def message_warning(text):
'''
Generate a warning.
'''
message(f'warning: {text}')
def JM_update_stream(doc, obj, buffer_, compress):
'''
update a stream object
compress stream when beneficial
'''
if compress:
length, _ = mupdf.fz_buffer_storage(buffer_)
if length > 30: # ignore small stuff
buffer_compressed = JM_compress_buffer(buffer_)
assert isinstance(buffer_compressed, mupdf.FzBuffer)
if buffer_compressed.m_internal:
length_compressed, _ = mupdf.fz_buffer_storage(buffer_compressed)
if length_compressed < length: # was it worth the effort?
mupdf.pdf_dict_put(
obj,
mupdf.PDF_ENUM_NAME_Filter,
mupdf.PDF_ENUM_NAME_FlateDecode,
)
mupdf.pdf_update_stream(doc, obj, buffer_compressed, 1)
return
mupdf.pdf_update_stream(doc, obj, buffer_, 0)
def JM_xobject_from_page(pdfout, fsrcpage, xref, gmap):
'''
Make an XObject from a PDF page
For a positive xref assume that its object can be used instead
'''
assert isinstance(gmap, mupdf.PdfGraftMap), f'{type(gmap)=}'
if xref > 0:
xobj1 = mupdf.pdf_new_indirect(pdfout, xref, 0)
else:
srcpage = _as_pdf_page(fsrcpage.this)
spageref = srcpage.obj()
mediabox = mupdf.pdf_to_rect(mupdf.pdf_dict_get_inheritable(spageref, PDF_NAME('MediaBox')))
# Deep-copy resources object of source page
o = mupdf.pdf_dict_get_inheritable(spageref, PDF_NAME('Resources'))
if gmap.m_internal:
# use graftmap when possible
resources = mupdf.pdf_graft_mapped_object(gmap, o)
else:
resources = mupdf.pdf_graft_object(pdfout, o)
# get spgage contents source
res = JM_read_contents(spageref)
#-------------------------------------------------------------
# create XObject representing the source page
#-------------------------------------------------------------
xobj1 = mupdf.pdf_new_xobject(pdfout, mediabox, mupdf.FzMatrix(), mupdf.PdfObj(0), res)
# store spage contents
JM_update_stream(pdfout, xobj1, res, 1)
# store spage resources
mupdf.pdf_dict_put(xobj1, PDF_NAME('Resources'), resources)
return xobj1
def PySequence_Check(s):
return isinstance(s, (tuple, list))
def PySequence_Size(s):
return len(s)
# constants: error messages. These are also in extra.i.
#
MSG_BAD_ANNOT_TYPE = "bad annot type"
MSG_BAD_APN = "bad or missing annot AP/N"
MSG_BAD_ARG_INK_ANNOT = "arg must be seq of seq of float pairs"
MSG_BAD_ARG_POINTS = "bad seq of points"
MSG_BAD_BUFFER = "bad type: 'buffer'"
MSG_BAD_COLOR_SEQ = "bad color sequence"
MSG_BAD_DOCUMENT = "cannot open broken document"
MSG_BAD_FILETYPE = "bad filetype"
MSG_BAD_LOCATION = "bad location"
MSG_BAD_OC_CONFIG = "bad config number"
MSG_BAD_OC_LAYER = "bad layer number"
MSG_BAD_OC_REF = "bad 'oc' reference"
MSG_BAD_PAGEID = "bad page id"
MSG_BAD_PAGENO = "bad page number(s)"
MSG_BAD_PDFROOT = "PDF has no root"
MSG_BAD_RECT = "rect is infinite or empty"
MSG_BAD_TEXT = "bad type: 'text'"
MSG_BAD_XREF = "bad xref"
MSG_COLOR_COUNT_FAILED = "color count failed"
MSG_FILE_OR_BUFFER = "need font file or buffer"
MSG_FONT_FAILED = "cannot create font"
MSG_IS_NO_ANNOT = "is no annotation"
MSG_IS_NO_IMAGE = "is no image"
MSG_IS_NO_PDF = "is no PDF"
MSG_IS_NO_DICT = "object is no PDF dict"
MSG_PIX_NOALPHA = "source pixmap has no alpha"
MSG_PIXEL_OUTSIDE = "pixel(s) outside image"
JM_Exc_FileDataError = 'FileDataError'
PyExc_ValueError = 'ValueError'
def RAISEPY( msg, exc):
#JM_Exc_CurrentException=exc
#fz_throw(context, FZ_ERROR_GENERIC, msg)
raise Exception( msg)
def PyUnicode_DecodeRawUnicodeEscape(s, errors='strict'):
# FIXED: handle raw unicode escape sequences
if not s:
return ""
if isinstance(s, str):
rc = s.encode("utf8", errors=errors)
elif isinstance(s, bytes):
rc = s[:]
ret = rc.decode('raw_unicode_escape', errors=errors)
return ret
def CheckColor(c: OptSeq):
if c:
if (
type(c) not in (list, tuple)
or len(c) not in (1, 3, 4)
or min(c) < 0
or max(c) > 1
):
raise ValueError("need 1, 3 or 4 color components in range 0 to 1")
def CheckFont(page: Page, fontname: str) -> tuple:
"""Return an entry in the page's font list if reference name matches.
"""
for f in page.get_fonts():
if f[4] == fontname:
return f
def CheckFontInfo(doc: Document, xref: int) -> list:
"""Return a font info if present in the document.
"""
for f in doc.FontInfos:
if xref == f[0]:
return f
def CheckMarkerArg(quads: typing.Any) -> tuple:
if CheckRect(quads):
r = Rect(quads)
return (r.quad,)
if CheckQuad(quads):
return (quads,)
for q in quads:
if not (CheckRect(q) or CheckQuad(q)):
raise ValueError("bad quads entry")
return quads
def CheckMorph(o: typing.Any) -> bool:
if not bool(o):
return False
if not (type(o) in (list, tuple) and len(o) == 2):
raise ValueError("morph must be a sequence of length 2")
if not (len(o[0]) == 2 and len(o[1]) == 6):
raise ValueError("invalid morph param 0")
if not o[1][4] == o[1][5] == 0:
raise ValueError("invalid morph param 1")
return True
def CheckParent(o: typing.Any):
return
if not hasattr(o, "parent") or o.parent is None:
raise ValueError(f"orphaned object {type(o)=}: parent is None")
def CheckQuad(q: typing.Any) -> bool:
"""Check whether an object is convex, not empty quad-like.
It must be a sequence of 4 number pairs.
"""
try:
q0 = Quad(q)
except Exception:
if g_exceptions_verbose > 1: exception_info()
return False
return q0.is_convex
def CheckRect(r: typing.Any) -> bool:
"""Check whether an object is non-degenerate rect-like.
It must be a sequence of 4 numbers.
"""
try:
r = Rect(r)
except Exception:
if g_exceptions_verbose > 1: exception_info()
return False
return not (r.is_empty or r.is_infinite)
def ColorCode(c: typing.Union[list, tuple, float, None], f: str) -> str:
if not c:
return ""
if hasattr(c, "__float__"):
c = (c,)
CheckColor(c)
if len(c) == 1:
s = _format_g(c[0]) + " "
return s + "G " if f == "c" else s + "g "
if len(c) == 3:
s = _format_g(tuple(c)) + " "
return s + "RG " if f == "c" else s + "rg "
s = _format_g(tuple(c)) + " "
return s + "K " if f == "c" else s + "k "
def Page__add_text_marker(self, quads, annot_type):
pdfpage = self._pdf_page()
rotation = JM_page_rotation(pdfpage)
def final():
if rotation != 0:
mupdf.pdf_dict_put_int(pdfpage.obj(), PDF_NAME('Rotate'), rotation)
try:
if rotation != 0:
mupdf.pdf_dict_put_int(pdfpage.obj(), PDF_NAME('Rotate'), 0)
annot = mupdf.pdf_create_annot(pdfpage, annot_type)
for item in quads:
q = JM_quad_from_py(item)
mupdf.pdf_add_annot_quad_point(annot, q)
mupdf.pdf_update_annot(annot)
JM_add_annot_id(annot, "A")
final()
except Exception:
if g_exceptions_verbose: exception_info()
final()
return
return Annot(annot)
def PDF_NAME(x):
assert isinstance(x, str)
return getattr(mupdf, f'PDF_ENUM_NAME_{x}')
def UpdateFontInfo(doc: Document, info: typing.Sequence):
xref = info[0]
found = False
for i, fi in enumerate(doc.FontInfos):
if fi[0] == xref:
found = True
break
if found:
doc.FontInfos[i] = info
else:
doc.FontInfos.append(info)
def args_match(args, *types):
'''
Returns true if <args> matches <types>.
Each item in <types> is a type or tuple of types. Any of these types will
match an item in <args>. `None` will match anything in <args>. `type(None)`
will match an arg whose value is `None`.
'''
j = 0
for i in range(len(types)):
type_ = types[i]
if j >= len(args):
if isinstance(type_, tuple) and None in type_:
# arg is missing but has default value.
continue
else:
return False
if type_ is not None and not isinstance(args[j], type_):
return False
j += 1
if j != len(args):
return False
return True
def calc_image_matrix(width, height, tr, rotate, keep):
'''
# compute image insertion matrix
'''
trect = JM_rect_from_py(tr)
rot = mupdf.fz_rotate(rotate)
trw = trect.x1 - trect.x0
trh = trect.y1 - trect.y0
w = trw
h = trh
if keep:
large = max(width, height)
fw = width / large
fh = height / large
else:
fw = fh = 1
small = min(fw, fh)
if rotate != 0 and rotate != 180:
f = fw
fw = fh
fh = f
if fw < 1:
if trw / fw > trh / fh:
w = trh * small
h = trh
else:
w = trw
h = trw / small
elif fw != fh:
if trw / fw > trh / fh:
w = trh / small
h = trh
else:
w = trw
h = trw * small
else:
w = trw
h = trh
tmp = mupdf.fz_make_point(
(trect.x0 + trect.x1) / 2,
(trect.y0 + trect.y1) / 2,
)
mat = mupdf.fz_make_matrix(1, 0, 0, 1, -0.5, -0.5)
mat = mupdf.fz_concat(mat, rot)
mat = mupdf.fz_concat(mat, mupdf.fz_scale(w, h))
mat = mupdf.fz_concat(mat, mupdf.fz_translate(tmp.x, tmp.y))
return mat
def detect_super_script(line, ch):
if line.m_internal.wmode == 0 and line.m_internal.dir.x == 1 and line.m_internal.dir.y == 0:
return ch.m_internal.origin.y < line.m_internal.first_char.origin.y - ch.m_internal.size * 0.1
return 0
def dir_str(x):
ret = f'{x} {type(x)} ({len(dir(x))}):\n'
for i in dir(x):
ret += f' {i}\n'
return ret
def getTJstr(text: str, glyphs: typing.Union[list, tuple, None], simple: bool, ordering: int) -> str:
""" Return a PDF string enclosed in [] brackets, suitable for the PDF TJ
operator.
Notes:
The input string is converted to either 2 or 4 hex digits per character.
Args:
simple: no glyphs: 2-chars, use char codes as the glyph
glyphs: 2-chars, use glyphs instead of char codes (Symbol,
ZapfDingbats)
not simple: ordering < 0: 4-chars, use glyphs not char codes
ordering >=0: a CJK font! 4 chars, use char codes as glyphs
"""
if text.startswith("[<") and text.endswith(">]"): # already done
return text
if not bool(text):
return "[<>]"
if simple: # each char or its glyph is coded as a 2-byte hex
if glyphs is None: # not Symbol, not ZapfDingbats: use char code
otxt = "".join(["%02x" % ord(c) if ord(c) < 256 else "b7" for c in text])
else: # Symbol or ZapfDingbats: use glyphs
otxt = "".join(
["%02x" % glyphs[ord(c)][0] if ord(c) < 256 else "b7" for c in text]
)
return "[<" + otxt + ">]"
# non-simple fonts: each char or its glyph is coded as 4-byte hex
if ordering < 0: # not a CJK font: use the glyphs
otxt = "".join(["%04x" % glyphs[ord(c)][0] for c in text])
else: # CJK: use the char codes
otxt = "".join(["%04x" % ord(c) for c in text])
return "[<" + otxt + ">]"
def get_pdf_str(s: str) -> str:
""" Return a PDF string depending on its coding.
Notes:
Returns a string bracketed with either "()" or "<>" for hex values.
If only ascii then "(original)" is returned, else if only 8 bit chars
then "(original)" with interspersed octal strings \nnn is returned,
else a string "<FEFF[hexstring]>" is returned, where [hexstring] is the
UTF-16BE encoding of the original.
"""
if not bool(s):
return "()"
def make_utf16be(s):
r = bytearray([254, 255]) + bytearray(s, "UTF-16BE")
return "<" + r.hex() + ">" # brackets indicate hex
# The following either returns the original string with mixed-in
# octal numbers \nnn for chars outside the ASCII range, or returns
# the UTF-16BE BOM version of the string.
r = ""
for c in s:
oc = ord(c)
if oc > 255: # shortcut if beyond 8-bit code range
return make_utf16be(s)
if oc > 31 and oc < 127: # in ASCII range
if c in ("(", ")", "\\"): # these need to be escaped
r += "\\"
r += c
continue
if oc > 127: # beyond ASCII
r += "\\%03o" % oc
continue
# now the white spaces
if oc == 8: # backspace
r += "\\b"
elif oc == 9: # tab
r += "\\t"
elif oc == 10: # line feed
r += "\\n"
elif oc == 12: # form feed
r += "\\f"
elif oc == 13: # carriage return
r += "\\r"
else:
r += "\\267" # unsupported: replace by 0xB7
return "(" + r + ")"
def get_tessdata():
"""Detect Tesseract-OCR and return its language support folder.
This function can be used to enable OCR via Tesseract even if the
environment variable TESSDATA_PREFIX has not been set.
If the value of TESSDATA_PREFIX is None, the function tries to locate
Tesseract-OCR and fills the required variable.
Returns:
Folder name of tessdata if Tesseract-OCR is available, otherwise False.
"""
TESSDATA_PREFIX = os.getenv("TESSDATA_PREFIX")
if TESSDATA_PREFIX: # use environment variable if set
return TESSDATA_PREFIX
"""
Try to locate the tesseract-ocr installation.
"""
import subprocess
# Windows systems:
if sys.platform == "win32":
cp = subprocess.run("where tesseract", shell=1, capture_output=1, check=0, text=True)
response = cp.stdout.strip()
if cp.returncode or not response:
message("Tesseract-OCR is not installed")
return False
dirname = os.path.dirname(response) # path of tesseract.exe
tessdata = os.path.join(dirname, "tessdata") # language support
if os.path.exists(tessdata): # all ok?
return tessdata
else: # should not happen!
message("unexpected: Tesseract-OCR has no 'tessdata' folder")
return False
# Unix-like systems:
cp = subprocess.run("whereis tesseract-ocr", shell=1, capture_output=1, check=0, text=True)
response = cp.stdout.strip().split()
if cp.returncode or len(response) != 2: # if not 2 tokens: no tesseract-ocr
message("tesseract-ocr is not installed")
return False
# search tessdata in folder structure
dirname = response[1] # contains tesseract-ocr installation folder
tessdatas = glob.glob(f"{dirname}/*/tessdata")
tessdatas.sort()
if len(tessdatas) == 0:
message("unexpected: tesseract-ocr has no 'tessdata' folder")
return False
return tessdatas[-1]
def css_for_pymupdf_font(
fontcode: str, *, CSS: OptStr = None, archive: AnyType = None, name: OptStr = None
) -> str:
"""Create @font-face items for the given fontcode of pymupdf-fonts.
Adds @font-face support for fonts contained in package pymupdf-fonts.
Creates a CSS font-family for all fonts starting with string 'fontcode'.
Note:
The font naming convention in package pymupdf-fonts is "fontcode<sf>",
where the suffix "sf" is either empty or one of "it", "bo" or "bi".
These suffixes thus represent the regular, italic, bold or bold-italic
variants of a font. For example, font code "notos" refers to fonts
"notos" - "Noto Sans Regular"
"notosit" - "Noto Sans Italic"
"notosbo" - "Noto Sans Bold"
"notosbi" - "Noto Sans Bold Italic"
This function creates four CSS @font-face definitions and collectively
assigns the font-family name "notos" to them (or the "name" value).
All fitting font buffers of the pymupdf-fonts package are placed / added
to the archive provided as parameter.
To use the font in pymupdf.Story, execute 'set_font(fontcode)'. The correct
font weight (bold) or style (italic) will automatically be selected.
Expects and returns the CSS source, with the new CSS definitions appended.
Args:
fontcode: (str) font code for naming the font variants to include.
E.g. "fig" adds notos, notosi, notosb, notosbi fonts.
A maximum of 4 font variants is accepted.
CSS: (str) CSS string to add @font-face definitions to.
archive: (Archive, mandatory) where to place the font buffers.
name: (str) use this as family-name instead of 'fontcode'.
Returns:
Modified CSS, with appended @font-face statements for each font variant
of fontcode.
Fontbuffers associated with "fontcode" will be added to 'archive'.
"""
# @font-face template string
CSSFONT = "\n@font-face {font-family: %s; src: url(%s);%s%s}\n"
if not type(archive) is Archive:
raise ValueError("'archive' must be an Archive")
if CSS is None:
CSS = ""
# select font codes starting with the pass-in string
font_keys = [k for k in fitz_fontdescriptors.keys() if k.startswith(fontcode)]
if font_keys == []:
raise ValueError(f"No font code '{fontcode}' found in pymupdf-fonts.")
if len(font_keys) > 4:
raise ValueError("fontcode too short")
if name is None: # use this name for font-family
name = fontcode
for fkey in font_keys:
font = fitz_fontdescriptors[fkey]
bold = font["bold"] # determine font property
italic = font["italic"] # determine font property
fbuff = font["loader"]() # load the fontbuffer
archive.add(fbuff, fkey) # update the archive
bold_text = "font-weight: bold;" if bold else ""
italic_text = "font-style: italic;" if italic else ""
CSS += CSSFONT % (name, fkey, bold_text, italic_text)
return CSS
def get_text_length(text: str, fontname: str ="helv", fontsize: float =11, encoding: int =0) -> float:
"""Calculate length of a string for a built-in font.
Args:
fontname: name of the font.
fontsize: font size points.
encoding: encoding to use, 0=Latin (default), 1=Greek, 2=Cyrillic.
Returns:
(float) length of text.
"""
fontname = fontname.lower()
basename = Base14_fontdict.get(fontname, None)
glyphs = None
if basename == "Symbol":
glyphs = symbol_glyphs
if basename == "ZapfDingbats":
glyphs = zapf_glyphs
if glyphs is not None:
w = sum([glyphs[ord(c)][1] if ord(c) < 256 else glyphs[183][1] for c in text])
return w * fontsize
if fontname in Base14_fontdict.keys():
return util_measure_string(
text, Base14_fontdict[fontname], fontsize, encoding
)
if fontname in (
"china-t",
"china-s",
"china-ts",
"china-ss",
"japan",
"japan-s",
"korea",
"korea-s",
):
return len(text) * fontsize
raise ValueError("Font '%s' is unsupported" % fontname)
def image_profile(img: typing.ByteString) -> dict:
""" Return basic properties of an image.
Args:
img: bytes, bytearray, io.BytesIO object or an opened image file.
Returns:
A dictionary with keys width, height, colorspace.n, bpc, type, ext and size,
where 'type' is the MuPDF image type (0 to 14) and 'ext' the suitable
file extension.
"""
if type(img) is io.BytesIO:
stream = img.getvalue()
elif hasattr(img, "read"):
stream = img.read()
elif type(img) in (bytes, bytearray):
stream = img
else:
raise ValueError("bad argument 'img'")
return TOOLS.image_profile(stream)
def jm_append_merge(dev):
'''
Append current path to list or merge into last path of the list.
(1) Append if first path, different item lists or not a 'stroke' version
of previous path
(2) If new path has the same items, merge its content into previous path
and change path["type"] to "fs".
(3) If "out" is callable, skip the previous and pass dictionary to it.
'''
#log(f'{getattr(dev, "pathdict", None)=}')
assert isinstance(dev.out, list)
#log( f'{dev.out=}')
if callable(dev.method) or dev.method: # function or method
# callback.
if dev.method is None:
# fixme, this surely cannot happen?
assert 0
#resp = PyObject_CallFunctionObjArgs(out, dev.pathdict, NULL)
else:
#log(f'calling {dev.out=} {dev.method=} {dev.pathdict=}')
resp = getattr(dev.out, dev.method)(dev.pathdict)
if not resp:
message("calling cdrawings callback function/method failed!")
dev.pathdict = None
return
def append():
#log(f'jm_append_merge(): clearing dev.pathdict')
dev.out.append(dev.pathdict.copy())
dev.pathdict.clear()
assert isinstance(dev.out, list)
len_ = len(dev.out) # len of output list so far
#log('{len_=}')
if len_ == 0: # always append first path
return append()
#log(f'{getattr(dev, "pathdict", None)=}')
thistype = dev.pathdict[ dictkey_type]
#log(f'{thistype=}')
if thistype != 's': # if not stroke, then append
return append()
prev = dev.out[ len_-1] # get prev path
#log( f'{prev=}')
prevtype = prev[ dictkey_type]
#log( f'{prevtype=}')
if prevtype != 'f': # if previous not fill, append
return append()
# last check: there must be the same list of items for "f" and "s".
previtems = prev[ dictkey_items]
thisitems = dev.pathdict[ dictkey_items]
if previtems != thisitems:
return append()
#rc = PyDict_Merge(prev, dev.pathdict, 0); // merge with no override
try:
for k, v in dev.pathdict.items():
if k not in prev:
prev[k] = v
rc = 0
except Exception:
if g_exceptions_verbose: exception_info()
#raise
rc = -1
if rc == 0:
prev[ dictkey_type] = 'fs'
dev.pathdict.clear()
else:
message("could not merge stroke and fill path")
append()
def jm_bbox_add_rect( dev, ctx, rect, code):
if not dev.layers:
dev.result.append( (code, JM_py_from_rect(rect)))
else:
dev.result.append( (code, JM_py_from_rect(rect), dev.layer_name))
def jm_bbox_fill_image( dev, ctx, image, ctm, alpha, color_params):
r = mupdf.FzRect(mupdf.FzRect.Fixed_UNIT)
r = mupdf.ll_fz_transform_rect( r.internal(), ctm)
jm_bbox_add_rect( dev, ctx, r, "fill-image")
def jm_bbox_fill_image_mask( dev, ctx, image, ctm, colorspace, color, alpha, color_params):
try:
jm_bbox_add_rect( dev, ctx, mupdf.ll_fz_transform_rect(mupdf.fz_unit_rect, ctm), "fill-imgmask")
except Exception:
if g_exceptions_verbose: exception_info()
raise
def jm_bbox_fill_path( dev, ctx, path, even_odd, ctm, colorspace, color, alpha, color_params):
even_odd = True if even_odd else False
try:
jm_bbox_add_rect( dev, ctx, mupdf.ll_fz_bound_path(path, None, ctm), "fill-path")
except Exception:
if g_exceptions_verbose: exception_info()
raise
def jm_bbox_fill_shade( dev, ctx, shade, ctm, alpha, color_params):
try:
jm_bbox_add_rect( dev, ctx, mupdf.ll_fz_bound_shade( shade, ctm), "fill-shade")
except Exception:
if g_exceptions_verbose: exception_info()
raise
def jm_bbox_stroke_text( dev, ctx, text, stroke, ctm, *args):
try:
jm_bbox_add_rect( dev, ctx, mupdf.ll_fz_bound_text( text, stroke, ctm), "stroke-text")
except Exception:
if g_exceptions_verbose: exception_info()
raise
def jm_bbox_fill_text( dev, ctx, text, ctm, *args):
try:
jm_bbox_add_rect( dev, ctx, mupdf.ll_fz_bound_text( text, None, ctm), "fill-text")
except Exception:
if g_exceptions_verbose: exception_info()
raise
def jm_bbox_ignore_text( dev, ctx, text, ctm):
jm_bbox_add_rect( dev, ctx, mupdf.ll_fz_bound_text(text, None, ctm), "ignore-text")
def jm_bbox_stroke_path( dev, ctx, path, stroke, ctm, colorspace, color, alpha, color_params):
try:
jm_bbox_add_rect( dev, ctx, mupdf.ll_fz_bound_path( path, stroke, ctm), "stroke-path")
except Exception:
if g_exceptions_verbose: exception_info()
raise
def jm_checkquad(dev):
'''
Check whether the last 4 lines represent a quad.
Because of how we count, the lines are a polyline already, i.e. last point
of a line equals 1st point of next line.
So we check for a polygon (last line's end point equals start point).
If not true we return 0.
'''
#log(f'{getattr(dev, "pathdict", None)=}')
items = dev.pathdict[ dictkey_items]
len_ = len(items)
f = [0] * 8 # coordinates of the 4 corners
# fill the 8 floats in f, start from items[-4:]
for i in range( 4): # store line start points
line = items[ len_ - 4 + i]
temp = JM_point_from_py( line[1])
f[i * 2] = temp.x
f[i * 2 + 1] = temp.y
lp = JM_point_from_py( line[ 2])
if lp.x != f[0] or lp.y != f[1]:
# not a polygon!
#dev.linecount -= 1
return 0
# we have detected a quad
dev.linecount = 0 # reset this
# a quad item is ("qu", (ul, ur, ll, lr)), where the tuple items
# are pairs of floats representing a quad corner each.
# relationship of float array to quad points:
# (0, 1) = ul, (2, 3) = ll, (6, 7) = ur, (4, 5) = lr
q = mupdf.fz_make_quad(f[0], f[1], f[6], f[7], f[2], f[3], f[4], f[5])
rect = ('qu', JM_py_from_quad(q))
items[ len_ - 4] = rect # replace item -4 by rect
del items[ len_ - 3 : len_] # delete remaining 3 items
return 1
def jm_checkrect(dev):
'''
Check whether the last 3 path items represent a rectangle.
Returns 1 if we have modified the path, otherwise 0.
'''
#log(f'{getattr(dev, "pathdict", None)=}')
dev.linecount = 0 # reset line count
orientation = 0 # area orientation of rectangle
items = dev.pathdict[ dictkey_items]
len_ = len(items)
line0 = items[ len_ - 3]
ll = JM_point_from_py( line0[ 1])
lr = JM_point_from_py( line0[ 2])
# no need to extract "line1"!
line2 = items[ len_ - 1]
ur = JM_point_from_py( line2[ 1])
ul = JM_point_from_py( line2[ 2])
# Assumption:
# When decomposing rects, MuPDF always starts with a horizontal line,
# followed by a vertical line, followed by a horizontal line.
# First line: (ll, lr), third line: (ul, ur).
# If 1st line is below 3rd line, we record anti-clockwise (+1), else
# clockwise (-1) orientation.
if (0
or ll.y != lr.y
or ll.x != ul.x
or ur.y != ul.y
or ur.x != lr.x
):
return 0 # not a rectangle
# we have a rect, replace last 3 "l" items by one "re" item.
if ul.y < lr.y:
r = mupdf.fz_make_rect(ul.x, ul.y, lr.x, lr.y)
orientation = 1
else:
r = mupdf.fz_make_rect(ll.x, ll.y, ur.x, ur.y)
orientation = -1
rect = ( 're', JM_py_from_rect(r), orientation)
items[ len_ - 3] = rect # replace item -3 by rect
del items[ len_ - 2 : len_] # delete remaining 2 items
return 1
def jm_trace_text( dev, text, type_, ctm, colorspace, color, alpha, seqno):
span = text.head
while 1:
if not span:
break
jm_trace_text_span( dev, span, type_, ctm, colorspace, color, alpha, seqno)
span = span.next
def jm_trace_text_span(dev, span, type_, ctm, colorspace, color, alpha, seqno):
'''
jm_trace_text_span(fz_context *ctx, PyObject *out, fz_text_span *span, int type, fz_matrix ctm, fz_colorspace *colorspace, const float *color, float alpha, size_t seqno)
'''
out_font = None
assert isinstance( span, mupdf.fz_text_span)
span = mupdf.FzTextSpan( span)
assert isinstance( ctm, mupdf.fz_matrix)
ctm = mupdf.FzMatrix( ctm)
fontname = JM_font_name( span.font())
#float rgb[3];
#PyObject *chars = PyTuple_New(span->len);
mat = mupdf.fz_concat(span.trm(), ctm) # text transformation matrix
dir = mupdf.fz_transform_vector(mupdf.fz_make_point(1, 0), mat) # writing direction
fsize = math.sqrt(dir.x * dir.x + dir.y * dir.y) # font size
dir = mupdf.fz_normalize_vector(dir)
space_adv = 0
asc = JM_font_ascender( span.font())
dsc = JM_font_descender( span.font())
if asc < 1e-3: # probably Tesseract font
dsc = -0.1
asc = 0.9
# compute effective ascender / descender
ascsize = asc * fsize / (asc - dsc)
dscsize = dsc * fsize / (asc - dsc)
fflags = 0 # font flags
mono = mupdf.fz_font_is_monospaced( span.font())
fflags += mono * TEXT_FONT_MONOSPACED
fflags += mupdf.fz_font_is_italic( span.font()) * TEXT_FONT_ITALIC
fflags += mupdf.fz_font_is_serif( span.font()) * TEXT_FONT_SERIFED
fflags += mupdf.fz_font_is_bold( span.font()) * TEXT_FONT_BOLD
last_adv = 0
# walk through characters of span
span_bbox = mupdf.FzRect()
rot = mupdf.fz_make_matrix(dir.x, dir.y, -dir.y, dir.x, 0, 0)
if dir.x == -1: # left-right flip
rot.d = 1
chars = []
for i in range( span.m_internal.len):
adv = 0
if span.items(i).gid >= 0:
adv = mupdf.fz_advance_glyph( span.font(), span.items(i).gid, span.m_internal.wmode)
adv *= fsize
last_adv = adv
if span.items(i).ucs == 32:
space_adv = adv
char_orig = mupdf.fz_make_point(span.items(i).x, span.items(i).y)
char_orig = mupdf.fz_transform_point(char_orig, ctm)
m1 = mupdf.fz_make_matrix(1, 0, 0, 1, -char_orig.x, -char_orig.y)
m1 = mupdf.fz_concat(m1, rot)
m1 = mupdf.fz_concat(m1, mupdf.FzMatrix(1, 0, 0, 1, char_orig.x, char_orig.y))
x0 = char_orig.x
x1 = x0 + adv
if (
(mat.d > 0 and (dir.x == 1 or dir.x == -1))
or
(mat.b != 0 and mat.b == -mat.c)
): # up-down flip
y0 = char_orig.y + dscsize
y1 = char_orig.y + ascsize
else:
y0 = char_orig.y - ascsize
y1 = char_orig.y - dscsize
char_bbox = mupdf.fz_make_rect(x0, y0, x1, y1)
char_bbox = mupdf.fz_transform_rect(char_bbox, m1)
chars.append(
(
span.items(i).ucs,
span.items(i).gid,
(
char_orig.x,
char_orig.y,
),
(
char_bbox.x0,
char_bbox.y0,
char_bbox.x1,
char_bbox.y1,
),
)
)
if i > 0:
span_bbox = mupdf.fz_union_rect(span_bbox, char_bbox)
else:
span_bbox = char_bbox
chars = tuple(chars)
if not space_adv:
if not mono:
c, out_font = mupdf.fz_encode_character_with_fallback( span.font(), 32, 0, 0)
space_adv = mupdf.fz_advance_glyph(
span.font(),
c,
span.m_internal.wmode,
)
space_adv *= fsize
if not space_adv:
space_adv = last_adv
else:
space_adv = last_adv # for mono, any char width suffices
# make the span dictionary
span_dict = dict()
span_dict[ 'dir'] = JM_py_from_point(dir)
span_dict[ 'font'] = JM_EscapeStrFromStr(fontname)
span_dict[ 'wmode'] = span.m_internal.wmode
span_dict[ 'flags'] =fflags
span_dict[ "bidi_lvl"] =span.m_internal.bidi_level
span_dict[ "bidi_dir"] = span.m_internal.markup_dir
span_dict[ 'ascender'] = asc
span_dict[ 'descender'] = dsc
span_dict[ 'colorspace'] = 3
if colorspace:
rgb = mupdf.fz_convert_color(
mupdf.FzColorspace( mupdf.ll_fz_keep_colorspace( colorspace)),
color,
mupdf.fz_device_rgb(),
mupdf.FzColorspace(),
mupdf.FzColorParams(),
)
rgb = rgb[:3] # mupdf.fz_convert_color() always returns 4 items.
else:
rgb = (0, 0, 0)
if dev.linewidth > 0: # width of character border
linewidth = dev.linewidth
else:
linewidth = fsize * 0.05 # default: 5% of font size
#log(f'{dev.linewidth=:.4f} {fsize=:.4f} {linewidth=:.4f}')
span_dict[ 'color'] = rgb
span_dict[ 'size'] = fsize
span_dict[ "opacity"] = alpha
span_dict[ "linewidth"] = linewidth
span_dict[ "spacewidth"] = space_adv
span_dict[ 'type'] = type_
span_dict[ 'bbox'] = JM_py_from_rect(span_bbox)
span_dict[ 'layer'] = dev.layer_name
span_dict[ "seqno"] = seqno
span_dict[ 'chars'] = chars
#log(f'{span_dict=}')
dev.out.append( span_dict)
def jm_lineart_color(colorspace, color):
#log(f' ')
if colorspace:
try:
# Need to be careful to use a named Python object to ensure
# that the `params` we pass to mupdf.ll_fz_convert_color() is
# valid. E.g. doing:
#
# rgb = mupdf.ll_fz_convert_color(..., mupdf.FzColorParams().internal())
#
# - seems to end up with a corrupted `params`.
#
cs = mupdf.FzColorspace( mupdf.FzColorspace.Fixed_RGB)
cp = mupdf.FzColorParams()
rgb = mupdf.ll_fz_convert_color(
colorspace,
color,
cs.m_internal,
None,
cp.internal(),
)
except Exception:
if g_exceptions_verbose: exception_info()
raise
return rgb[:3]
return ()
def jm_lineart_drop_device(dev, ctx):
if isinstance(dev.out, list):
dev.out = []
dev.scissors = []
def jm_lineart_fill_path( dev, ctx, path, even_odd, ctm, colorspace, color, alpha, color_params):
#log(f'{getattr(dev, "pathdict", None)=}')
#log(f'jm_lineart_fill_path(): {dev.seqno=}')
even_odd = True if even_odd else False
try:
assert isinstance( ctm, mupdf.fz_matrix)
dev.ctm = mupdf.FzMatrix( ctm) # fz_concat(ctm, dev_ptm);
dev.path_type = trace_device_FILL_PATH
jm_lineart_path( dev, ctx, path)
if dev.pathdict is None:
return
#item_count = len(dev.pathdict[ dictkey_items])
#if item_count == 0:
# return
dev.pathdict[ dictkey_type] ="f"
dev.pathdict[ "even_odd"] = even_odd
dev.pathdict[ "fill_opacity"] = alpha
#log(f'setting dev.pathdict[ "closePath"] to false')
#dev.pathdict[ "closePath"] = False
dev.pathdict[ "fill"] = jm_lineart_color( colorspace, color)
dev.pathdict[ dictkey_rect] = JM_py_from_rect(dev.pathrect)
dev.pathdict[ "seqno"] = dev.seqno
#jm_append_merge(dev)
dev.pathdict[ 'layer'] = dev.layer_name
if dev.clips:
dev.pathdict[ 'level'] = dev.depth
jm_append_merge(dev)
dev.seqno += 1
#log(f'jm_lineart_fill_path() end: {getattr(dev, "pathdict", None)=}')
except Exception:
if g_exceptions_verbose: exception_info()
raise
# There are 3 text trace types:
# 0 - fill text (PDF Tr 0)
# 1 - stroke text (PDF Tr 1)
# 3 - ignore text (PDF Tr 3)
def jm_lineart_fill_text( dev, ctx, text, ctm, colorspace, color, alpha, color_params):
if 0:
log(f'{type(ctx)=} {ctx=}')
log(f'{type(dev)=} {dev=}')
log(f'{type(text)=} {text=}')
log(f'{type(ctm)=} {ctm=}')
log(f'{type(colorspace)=} {colorspace=}')
log(f'{type(color)=} {color=}')
log(f'{type(alpha)=} {alpha=}')
log(f'{type(color_params)=} {color_params=}')
jm_trace_text(dev, text, 0, ctm, colorspace, color, alpha, dev.seqno)
dev.seqno += 1
def jm_lineart_ignore_text(dev, text, ctm):
#log(f'{getattr(dev, "pathdict", None)=}')
jm_trace_text(dev, text, 3, ctm, None, None, 1, dev.seqno)
dev.seqno += 1
class Walker(mupdf.FzPathWalker2):
def __init__(self, dev):
super().__init__()
self.use_virtual_moveto()
self.use_virtual_lineto()
self.use_virtual_curveto()
self.use_virtual_closepath()
self.dev = dev
def closepath(self, ctx): # trace_close().
#log(f'Walker(): {self.dev.pathdict=}')
try:
if self.dev.linecount == 3:
if jm_checkrect(self.dev):
#log(f'end1: {self.dev.pathdict=}')
return
self.dev.linecount = 0 # reset # of consec. lines
if self.dev.havemove:
if self.dev.lastpoint != self.dev.firstpoint:
item = ("l", JM_py_from_point(self.dev.lastpoint),
JM_py_from_point(self.dev.firstpoint))
self.dev.pathdict[dictkey_items].append(item)
self.dev.lastpoint = self.dev.firstpoint
self.dev.pathdict["closePath"] = False
else:
#log('setting self.dev.pathdict[ "closePath"] to true')
self.dev.pathdict[ "closePath"] = True
#log(f'end2: {self.dev.pathdict=}')
self.dev.havemove = 0
except Exception:
if g_exceptions_verbose: exception_info()
raise
def curveto(self, ctx, x1, y1, x2, y2, x3, y3): # trace_curveto().
#log(f'Walker(): {self.dev.pathdict=}')
try:
self.dev.linecount = 0 # reset # of consec. lines
p1 = mupdf.fz_make_point(x1, y1)
p2 = mupdf.fz_make_point(x2, y2)
p3 = mupdf.fz_make_point(x3, y3)
p1 = mupdf.fz_transform_point(p1, self.dev.ctm)
p2 = mupdf.fz_transform_point(p2, self.dev.ctm)
p3 = mupdf.fz_transform_point(p3, self.dev.ctm)
self.dev.pathrect = mupdf.fz_include_point_in_rect(self.dev.pathrect, p1)
self.dev.pathrect = mupdf.fz_include_point_in_rect(self.dev.pathrect, p2)
self.dev.pathrect = mupdf.fz_include_point_in_rect(self.dev.pathrect, p3)
list_ = (
"c",
JM_py_from_point(self.dev.lastpoint),
JM_py_from_point(p1),
JM_py_from_point(p2),
JM_py_from_point(p3),
)
self.dev.lastpoint = p3
self.dev.pathdict[ dictkey_items].append( list_)
except Exception:
if g_exceptions_verbose: exception_info()
raise
def lineto(self, ctx, x, y): # trace_lineto().
#log(f'Walker(): {self.dev.pathdict=}')
try:
p1 = mupdf.fz_transform_point( mupdf.fz_make_point(x, y), self.dev.ctm)
self.dev.pathrect = mupdf.fz_include_point_in_rect( self.dev.pathrect, p1)
list_ = (
'l',
JM_py_from_point( self.dev.lastpoint),
JM_py_from_point(p1),
)
self.dev.lastpoint = p1
items = self.dev.pathdict[ dictkey_items]
items.append( list_)
self.dev.linecount += 1 # counts consecutive lines
if self.dev.linecount == 4 and self.dev.path_type != trace_device_FILL_PATH:
# shrink to "re" or "qu" item
jm_checkquad(self.dev)
except Exception:
if g_exceptions_verbose: exception_info()
raise
def moveto(self, ctx, x, y): # trace_moveto().
if 0 and isinstance(self.dev.pathdict, dict):
log(f'self.dev.pathdict:')
for n, v in self.dev.pathdict.items():
log( ' {type(n)=} {len(n)=} {n!r} {n}: {v!r}: {v}')
#log(f'Walker(): {type(self.dev.pathdict)=} {self.dev.pathdict=}')
try:
#log( '{=dev.ctm type(dev.ctm)}')
self.dev.lastpoint = mupdf.fz_transform_point(
mupdf.fz_make_point(x, y),
self.dev.ctm,
)
if mupdf.fz_is_infinite_rect( self.dev.pathrect):
self.dev.pathrect = mupdf.fz_make_rect(
self.dev.lastpoint.x,
self.dev.lastpoint.y,
self.dev.lastpoint.x,
self.dev.lastpoint.y,
)
self.dev.firstpoint = self.dev.lastpoint
self.dev.havemove = 1
self.dev.linecount = 0 # reset # of consec. lines
except Exception:
if g_exceptions_verbose: exception_info()
raise
def jm_lineart_path(dev, ctx, path):
'''
Create the "items" list of the path dictionary
* either create or empty the path dictionary
* reset the end point of the path
* reset count of consecutive lines
* invoke fz_walk_path(), which create the single items
* if no items detected, empty path dict again
'''
#log(f'{getattr(dev, "pathdict", None)=}')
try:
dev.pathrect = mupdf.FzRect( mupdf.FzRect.Fixed_INFINITE)
dev.linecount = 0
dev.lastpoint = mupdf.FzPoint( 0, 0)
dev.pathdict = dict()
dev.pathdict[ dictkey_items] = []
# First time we create a Walker instance is slow, e.g. 0.3s, then later
# times run in around 0.01ms. If Walker is defined locally instead of
# globally, each time takes 0.3s.
#
walker = Walker(dev)
# Unlike fz_run_page(), fz_path_walker callbacks are not passed
# a pointer to the struct, instead they get an arbitrary
# void*. The underlying C++ Director callbacks use this void* to
# identify the fz_path_walker instance so in turn we need to pass
# arg=walker.m_internal.
mupdf.fz_walk_path( mupdf.FzPath(mupdf.ll_fz_keep_path(path)), walker, walker.m_internal)
# Check if any items were added ...
if not dev.pathdict[ dictkey_items]:
dev.pathdict = None
except Exception:
if g_exceptions_verbose: exception_info()
raise
def jm_lineart_stroke_path( dev, ctx, path, stroke, ctm, colorspace, color, alpha, color_params):
#log(f'{dev.pathdict=} {dev.clips=}')
try:
assert isinstance( ctm, mupdf.fz_matrix)
dev.pathfactor = 1
if ctm.a != 0 and abs(ctm.a) == abs(ctm.d):
dev.pathfactor = abs(ctm.a)
elif ctm.b != 0 and abs(ctm.b) == abs(ctm.c):
dev.pathfactor = abs(ctm.b)
dev.ctm = mupdf.FzMatrix( ctm) # fz_concat(ctm, dev_ptm);
dev.path_type = trace_device_STROKE_PATH
jm_lineart_path( dev, ctx, path)
if dev.pathdict is None:
return
dev.pathdict[ dictkey_type] = 's'
dev.pathdict[ 'stroke_opacity'] = alpha
dev.pathdict[ 'color'] = jm_lineart_color( colorspace, color)
dev.pathdict[ dictkey_width] = dev.pathfactor * stroke.linewidth
dev.pathdict[ 'lineCap'] = (
stroke.start_cap,
stroke.dash_cap,
stroke.end_cap,
)
dev.pathdict[ 'lineJoin'] = dev.pathfactor * stroke.linejoin
if 'closePath' not in dev.pathdict:
#log('setting dev.pathdict["closePath"] to false')
dev.pathdict['closePath'] = False
# output the "dashes" string
if stroke.dash_len:
buff = mupdf.fz_new_buffer( 256)
mupdf.fz_append_string( buff, "[ ") # left bracket
for i in range( stroke.dash_len):
# We use mupdf python's SWIG-generated floats_getitem() fn to
# access float *stroke.dash_list[].
value = mupdf.floats_getitem( stroke.dash_list, i) # stroke.dash_list[i].
mupdf.fz_append_string( buff, f'{_format_g(dev.pathfactor * value)} ')
mupdf.fz_append_string( buff, f'] {_format_g(dev.pathfactor * stroke.dash_phase)}')
dev.pathdict[ 'dashes'] = buff
else:
dev.pathdict[ 'dashes'] = '[] 0'
dev.pathdict[ dictkey_rect] = JM_py_from_rect(dev.pathrect)
dev.pathdict['layer'] = dev.layer_name
dev.pathdict[ 'seqno'] = dev.seqno
if dev.clips:
dev.pathdict[ 'level'] = dev.depth
jm_append_merge(dev)
dev.seqno += 1
except Exception:
if g_exceptions_verbose: exception_info()
raise
def jm_lineart_clip_path(dev, ctx, path, even_odd, ctm, scissor):
if not dev.clips:
return
dev.ctm = mupdf.FzMatrix(ctm) # fz_concat(ctm, trace_device_ptm);
dev.path_type = trace_device_CLIP_PATH
jm_lineart_path(dev, ctx, path)
if dev.pathdict is None:
return
dev.pathdict[ dictkey_type] = 'clip'
dev.pathdict[ 'even_odd'] = bool(even_odd)
if 'closePath' not in dev.pathdict:
#log(f'setting dev.pathdict["closePath"] to False')
dev.pathdict['closePath'] = False
dev.pathdict['scissor'] = JM_py_from_rect(compute_scissor(dev))
dev.pathdict['level'] = dev.depth
dev.pathdict['layer'] = dev.layer_name
jm_append_merge(dev)
dev.depth += 1
def jm_lineart_clip_stroke_path(dev, ctx, path, stroke, ctm, scissor):
if not dev.clips:
return
dev.ctm = mupdf.FzMatrix(ctm) # fz_concat(ctm, trace_device_ptm);
dev.path_type = trace_device_CLIP_STROKE_PATH
jm_lineart_path(dev, ctx, path)
if dev.pathdict is None:
return
dev.pathdict['dictkey_type'] = 'clip'
dev.pathdict['even_odd'] = None
if 'closePath' not in dev.pathdict:
#log(f'setting dev.pathdict["closePath"] to False')
dev.pathdict['closePath'] = False
dev.pathdict['scissor'] = JM_py_from_rect(compute_scissor(dev))
dev.pathdict['level'] = dev.depth
dev.pathdict['layer'] = dev.layer_name
jm_append_merge(dev)
dev.depth += 1
def jm_lineart_clip_stroke_text(dev, ctx, text, stroke, ctm, scissor):
if not dev.clips:
return
compute_scissor(dev)
dev.depth += 1
def jm_lineart_clip_text(dev, ctx, text, ctm, scissor):
if not dev.clips:
return
compute_scissor(dev)
dev.depth += 1
def jm_lineart_clip_image_mask( dev, ctx, image, ctm, scissor):
if not dev.clips:
return
compute_scissor(dev)
dev.depth += 1
def jm_lineart_pop_clip(dev, ctx):
if not dev.clips or not dev.scissors:
return
len_ = len(dev.scissors)
if len_ < 1:
return
del dev.scissors[-1]
dev.depth -= 1
def jm_lineart_begin_layer(dev, ctx, name):
if name:
dev.layer_name = name
else:
dev.layer_name = ""
def jm_lineart_end_layer(dev, ctx):
dev.layer_name = ""
def jm_lineart_begin_group(dev, ctx, bbox, cs, isolated, knockout, blendmode, alpha):
#log(f'{dev.pathdict=} {dev.clips=}')
if not dev.clips:
return
dev.pathdict = { # Py_BuildValue("{s:s,s:N,s:N,s:N,s:s,s:f,s:i,s:N}",
"type": "group",
"rect": JM_py_from_rect(bbox),
"isolated": bool(isolated),
"knockout": bool(knockout),
"blendmode": mupdf.fz_blendmode_name(blendmode),
"opacity": alpha,
"level": dev.depth,
"layer": dev.layer_name
}
jm_append_merge(dev)
dev.depth += 1
def jm_lineart_end_group(dev, ctx):
#log(f'{dev.pathdict=} {dev.clips=}')
if not dev.clips:
return
dev.depth -= 1
def jm_lineart_stroke_text(dev, ctx, text, stroke, ctm, colorspace, color, alpha, color_params):
jm_trace_text(dev, text, 1, ctm, colorspace, color, alpha, dev.seqno)
dev.seqno += 1
def jm_dev_linewidth( dev, ctx, path, stroke, matrix, colorspace, color, alpha, color_params):
dev.linewidth = stroke.linewidth
jm_increase_seqno( dev, ctx)
def jm_increase_seqno( dev, ctx, *vargs):
try:
dev.seqno += 1
except Exception:
if g_exceptions_verbose: exception_info()
raise
def planish_line(p1: point_like, p2: point_like) -> Matrix:
"""Compute matrix which maps line from p1 to p2 to the x-axis, such that it
maintains its length and p1 * matrix = Point(0, 0).
Args:
p1, p2: point_like
Returns:
Matrix which maps p1 to Point(0, 0) and p2 to a point on the x axis at
the same distance to Point(0,0). Will always combine a rotation and a
transformation.
"""
p1 = Point(p1)
p2 = Point(p2)
return Matrix(util_hor_matrix(p1, p2))
class JM_image_reporter_Filter(mupdf.PdfFilterOptions2):
def __init__(self):
super().__init__()
self.use_virtual_image_filter()
def image_filter( self, ctx, ctm, name, image):
assert isinstance(ctm, mupdf.fz_matrix)
JM_image_filter(self, mupdf.FzMatrix(ctm), name, image)
if mupdf_cppyy:
# cppyy doesn't appear to treat returned None as nullptr,
# resulting in obscure 'python exception' exception.
return 0
class JM_new_bbox_device_Device(mupdf.FzDevice2):
def __init__(self, result, layers):
super().__init__()
self.result = result
self.layers = layers
self.use_virtual_fill_path()
self.use_virtual_stroke_path()
self.use_virtual_fill_text()
self.use_virtual_stroke_text()
self.use_virtual_ignore_text()
self.use_virtual_fill_shade()
self.use_virtual_fill_image()
self.use_virtual_fill_image_mask()
self.use_virtual_begin_layer()
self.use_virtual_end_layer()
begin_layer = jm_lineart_begin_layer
end_layer = jm_lineart_end_layer
fill_path = jm_bbox_fill_path
stroke_path = jm_bbox_stroke_path
fill_text = jm_bbox_fill_text
stroke_text = jm_bbox_stroke_text
ignore_text = jm_bbox_ignore_text
fill_shade = jm_bbox_fill_shade
fill_image = jm_bbox_fill_image
fill_image_mask = jm_bbox_fill_image_mask
class JM_new_output_fileptr_Output(mupdf.FzOutput2):
def __init__(self, bio):
super().__init__()
self.bio = bio
self.use_virtual_write()
self.use_virtual_seek()
self.use_virtual_tell()
self.use_virtual_truncate()
def seek( self, ctx, offset, whence):
return self.bio.seek( offset, whence)
def tell( self, ctx):
ret = self.bio.tell()
return ret
def truncate( self, ctx):
return self.bio.truncate()
def write(self, ctx, data_raw, data_length):
data = mupdf.raw_to_python_bytes(data_raw, data_length)
return self.bio.write(data)
def compute_scissor(dev):
'''
Every scissor of a clip is a sub rectangle of the preceding clip scissor
if the clip level is larger.
'''
if dev.scissors is None:
dev.scissors = list()
num_scissors = len(dev.scissors)
if num_scissors > 0:
last_scissor = dev.scissors[num_scissors-1]
scissor = JM_rect_from_py(last_scissor)
scissor = mupdf.fz_intersect_rect(scissor, dev.pathrect)
else:
scissor = dev.pathrect
dev.scissors.append(JM_py_from_rect(scissor))
return scissor
class JM_new_lineart_device_Device(mupdf.FzDevice2):
'''
LINEART device for Python method Page.get_cdrawings()
'''
#log(f'JM_new_lineart_device_Device()')
def __init__(self, out, clips, method):
#log(f'JM_new_lineart_device_Device.__init__()')
super().__init__()
# fixme: this results in "Unexpected call of unimplemented virtual_fnptrs fn FzDevice2::drop_device().".
#self.use_virtual_drop_device()
self.use_virtual_fill_path()
self.use_virtual_stroke_path()
self.use_virtual_clip_path()
self.use_virtual_clip_image_mask()
self.use_virtual_clip_stroke_path()
self.use_virtual_clip_stroke_text()
self.use_virtual_clip_text()
self.use_virtual_fill_text
self.use_virtual_stroke_text
self.use_virtual_ignore_text
self.use_virtual_fill_shade()
self.use_virtual_fill_image()
self.use_virtual_fill_image_mask()
self.use_virtual_pop_clip()
self.use_virtual_begin_group()
self.use_virtual_end_group()
self.use_virtual_begin_layer()
self.use_virtual_end_layer()
self.out = out
self.seqno = 0
self.depth = 0
self.clips = clips
self.method = method
self.scissors = None
self.layer_name = "" # optional content name
self.pathrect = None
self.linewidth = 0
self.ptm = mupdf.FzMatrix()
self.ctm = mupdf.FzMatrix()
self.rot = mupdf.FzMatrix()
self.lastpoint = mupdf.FzPoint()
self.firstpoint = mupdf.FzPoint()
self.havemove = 0
self.pathrect = mupdf.FzRect()
self.pathfactor = 0
self.linecount = 0
self.path_type = 0
#drop_device = jm_lineart_drop_device
fill_path = jm_lineart_fill_path
stroke_path = jm_lineart_stroke_path
clip_image_mask = jm_lineart_clip_image_mask
clip_path = jm_lineart_clip_path
clip_stroke_path = jm_lineart_clip_stroke_path
clip_text = jm_lineart_clip_text
clip_stroke_text = jm_lineart_clip_stroke_text
fill_text = jm_increase_seqno
stroke_text = jm_increase_seqno
ignore_text = jm_increase_seqno
fill_shade = jm_increase_seqno
fill_image = jm_increase_seqno
fill_image_mask = jm_increase_seqno
pop_clip = jm_lineart_pop_clip
begin_group = jm_lineart_begin_group
end_group = jm_lineart_end_group
begin_layer = jm_lineart_begin_layer
end_layer = jm_lineart_end_layer
class JM_new_texttrace_device(mupdf.FzDevice2):
'''
Trace TEXT device for Python method Page.get_texttrace()
'''
def __init__(self, out):
super().__init__()
self.use_virtual_fill_path()
self.use_virtual_stroke_path()
self.use_virtual_fill_text()
self.use_virtual_stroke_text()
self.use_virtual_ignore_text()
self.use_virtual_fill_shade()
self.use_virtual_fill_image()
self.use_virtual_fill_image_mask()
self.use_virtual_begin_layer()
self.use_virtual_end_layer()
self.out = out
self.seqno = 0
self.depth = 0
self.clips = 0
self.method = None
self.seqno = 0
self.pathdict = dict()
self.scissors = list()
self.linewidth = 0
self.ptm = mupdf.FzMatrix()
self.ctm = mupdf.FzMatrix()
self.rot = mupdf.FzMatrix()
self.lastpoint = mupdf.FzPoint()
self.pathrect = mupdf.FzRect()
self.pathfactor = 0
self.linecount = 0
self.path_type = 0
self.layer_name = ""
fill_path = jm_increase_seqno
stroke_path = jm_dev_linewidth
fill_text = jm_lineart_fill_text
stroke_text = jm_lineart_stroke_text
ignore_text = jm_lineart_ignore_text
fill_shade = jm_increase_seqno
fill_image = jm_increase_seqno
fill_image_mask = jm_increase_seqno
begin_layer = jm_lineart_begin_layer
end_layer = jm_lineart_end_layer
def _get_glyph_text() -> bytes:
'''
Adobe Glyph List function
'''
import base64
import gzip
return gzip.decompress(base64.b64decode(
b'H4sIABmRaF8C/7W9SZfjRpI1useviPP15utzqroJgBjYWhEkKGWVlKnOoapVO0YQEYSCJE'
b'IcMhT569+9Ppibg8xevHdeSpmEXfPBfDZ3N3f/t7u//r//k/zb3WJ4eTv2T9vzXTaZZH/N'
b'Junsbr4Z7ru7/7s9n1/+6z//8/X19T/WRP7jYdj/57//R/Jv8Pax2/Sn87G/v5z74XC3Pm'
b'zuLqfurj/cnYbL8aEzyH1/WB/f7h6H4/70l7vX/ry9G47wzK/hcr7bD5v+sX9YM4i/3K2P'
b'3d1Ld9z353O3uXs5Dl/7DT7O2/UZ/3Tw9zjsdsNrf3i6exgOm57eTsbbvjv/1w2xTnfDo5'
b'fnYdjA3eV0vjt25zXkRJB36/vhKwN+kEw4DOf+ofsLuP3pboewGISO7bAxPkUU+EaUD7t1'
b'v++O/3FTCESmcsILgQRuLhDs/w857lz6NsPDZd8dzmtfSP85HO8GcI53+/W5O/br3QkeJa'
b'9NERmPKgE2Ue+73vgj97Ded5TH1pPDEFCT4/35RFFtAMORMezXb3dwiioCsYe77rABjjCO'
b'jHs/nLs7mx3wuYFYX+HsEQyTfHg/DY/nVxa0rzmnl+6BVQfeegTyemSlOdjqczqJ0J9/ev'
b'fp7tOH1ed/zj+2d/j+9eOHf7xbtsu75jcw27vFh19/+/jux58+3/304edl+/HT3fz9kq3i'
b'w/vPH981Xz5/APR/5p/g9/+Qhb+/3bX/8+vH9tOnuw8f79798uvP7xAcwv84f//5XfvpL/'
b'D97v3i5y/Ld+9//Msdgrh7/+Hz3c/vfnn3GQ4/f/iLifja492HFbz+0n5c/ARg3rz7+d3n'
b'30ycq3ef3zO+FSKc3/06//j53eLLz/OPd79++fjrh0/tHRIHr8t3nxY/z9/90i7/AxIg1r'
b'v2H+37z3effpr//PPN1CIF47Q2LUSdNz+3NjakdvnuY7v4/BcEGb4WyEPI+DMT++nXdvEO'
b'n8iWFomaf/ztL8wZhPqp/e8vcAbm3XL+y/xHpPH/xlnDejXKHJTQ4svH9hdK/mF19+lL8+'
b'nzu89fPrd3P374sDSZ/qn9+I93i/bTD/D+8wcWxOruy6f2L4jl89xEjkCQaZ9+4Hfz5dM7'
b'k33v3n9uP3788uvndx/e/zu8/vThn8ggSDqH56XJ6Q/vTZKRVx8+/sZgmRemIP5y98+fWu'
b'Ao8vc+z+bMjE/Iu8Vn7RBxIis/q7TevW9//Pndj+37RWuz/AND+ue7T+2/o+zefaKTdzbq'
b'f84R7xeTdJYYJLOf7z4xq11N/osp2bt3q7v58h/vKLxzjtrw6Z2rOSbzFj+5rEd7+P84UL'
b'xH8/6vO/lj2/6Pu7eX7d3P6C3Y2tb3u+7ua3dkA/yvu+w/JqyV6GeUt0/dy7nb36MjySZ/'
b'MUMO3Hz5+LNycsdx54SB5wmN/XJvRh0z/vz1/PaCf4Zhd/rP9dPur/j7eDDtfIV+dX3+r7'
b'vz63B36vb9w7AbDn/ddLseown7kr7bbU4YIhD6/03//e7JiM0O669/vbyg1/hPdKLd8WGN'
b'PmnXoSs52h5200OGk/WW/fvdl0NvhpHTw3q3Pt59Xe8uCOARA8ydCcX433Z/rjfonfbrnf'
b'hP5j9MJtM0mbf4XZT4XT9czt0Pk3S1ALFfPxyHA6g2A3WCz90Pq6qFO+dsskjdtzAB3B+7'
b'rwwDeWi/reu0nbcOeMBostv1Dz9MpsuJwzbD+b5DcuGuKR32dFx/pcfGO9oOw7MZlAj64M'
b'/9bmOAaTJ/WFuJF0t898eHXfdDNmV4JC77x133J8XONCDiTTWq5JkvNMMLNY9C1ZLNa82R'
b'rIki9ULP50AZ/6pczOyn92DSE3IqRSZs7nc2+gmqKMi+O3an/sQkTQOpszcLsBTnsg2gSE'
b'f/KskTQ4YaANrFPFn4b/ELIEo/Iu2jQkbg/QEtEJXe1Y6MtWP3sl3/MMlnqf08D4cBaclr'
b'5KzEzHTuyXhZPyCXVhkcD0/DoXsmEwEfoWVQqsJ+Sg2eW9qniOGQFqHh3n+XCNMWCMLJ3b'
b'c4BPB2vz5CYenXkKjI06Rhu8mSJlSxKmmQX+uHB6g1jC0ztEQ+TRqdISmC6A46TLiH/sfM'
b'wBczE0mo4WrXHzoJpUyaKCvglLnpJC1XiEWSBN55eIHcDChLFpQ4TxZrHWkL2mUXwl6Yto'
b'N6OLefEmyRLHy7mizwDT1yt1szryqhfCOa1AJJBtKVZFRtCd8WU3pATvFrbr5cHlo6Dome'
b'tzoF0xmAbn3/vF2fgKgcbhbkKCCrCKBYETp0uZt+2siJ5pSGc92+kOVgbLVIOREE/rw+jc'
b'JfNGSxGWBysYMmOzxrCU3qelSBOUV1VQCf456kXEGaqB4gykGJUKTJQupBnixZ9NNk+S+2'
b'ihS/0kkCjOoD6ccjhCO3niVLKfYW367Y0xY90TIU6MwSVkRfVdMM6HFYsxzpPGobc0NLrV'
b'4ky6htQIoOA9rLmWTeIupuh6aRZaij5vPp2LH15zO49PmEMH1niBrcCCWd60KgH00/Bmgp'
b'kM8t9NzL/mm930scS/j7XYuHlr2MGiXkiwoDQvnESoFVyfKEarx1uSGFA7ehkULobywiRP'
b'BNiqgAcbOCo9MFRwtGp1GVn6wSDuzTImllwJ65b2mcAPyAjZxvfcTpHN+2xC0bZboApKt6'
b'joBDPZhbIgyyEeD7B7Sx9kZ1qTWqKgeUkvZ66MUI1N4eejGytzeG3kgUP/QumFyVWyD1+E'
b'pSja9NICVYYqbrSkvzJV2Xo0WhQfIedV+EsGU0rd23hAogyuUKtNZ7kBjOxTEPBT9LS/Cv'
b'BlfE32OqDgVzo+JFfWt3uqkhATv4OEhYCFtGXrRhR/jCY7Is4kuCVWavQ0QdiVoDqoiute'
b'kS9K0eFjpDy3E8nc75EdVjKGbtgVmg+1KkWtQAVp/hpaPQM1SNl1O/YwryWeEJUS3gUkeb'
b'wTnzDLP+DdtgG0jtClLrXh86SHu6mQoIb1r5HM1KWjmksEN7xQ9VsjVpEQ1ezvA7gUqMD+'
b'97RcpruAv3Le0G8V2Oww/ZBDpq+40xQxPBh2/G6D1BqRSiKq7YJ5TJKjTdJlnpDjptk1U0'
b'phVwrbvkabJy/S5Ut1UPnyELqgwIovM1Cm6jCoGgMDERdp6sJJ/K5EeKViU/Nqc/Lutj90'
b'OeYwD8UVS6Kb7RNzMrc/sZhqsZmYenfh3EnCc/StfWJj9KniAe0WFSKFE/hpxYWEK0k5TA'
b'wIh806Z72+hRd37UjZ50NJBBxu16o3UD+N1iHrjZ7LpRfab42+5KJ5gZH5eX8+WomxFq+Y'
b'++BBALJnWqVgGIRywArlFjJgefUXkgf/142NpPKQ84le/KfdtYs1kD2gjLDJ0mP7Hg6uSn'
b'tEb8P2TFYmW+p/xGo+B3kfK7SX7CQF4ZPE1++lUKGh3sT+tbAx3G5J/WN5WyDIzj5tQ/ae'
b'cZYrMDKqraT6b8fWshK2gxGcINBb+0hBQ8uuifpPuHY4SlmwhqwU+qg6frKFcRttbIphPQ'
b'R9WCwJesxfcF85bjZb9bX84siFWEiBYBh98kv1AF3jHTZ8k7PUvMVsm7v0F+TCjefdF4m7'
b'wTJWDpvmXIAeBbSrZI3on2gcBCFrWWCAN8BEhYRFXlK5N3elStQapRdRVIP8hQ0huaNirZ'
b'u6sBmN5NW8wn5kvaoqNFjZgn77qrpQeIFrXXInn3eFw/o62hZ8IU7Z2M0Qv3LREDiNQOJK'
b'vXQZEej8mQoT9th+NZO0TxyYCL+ukInW4UZFS14AO1SrX3Jnk36ByH4DIyMjMHO/jMzJfq'
b'MEsDhNLI0VCJyIAEUiopfEt7xzj2zk2XU9T0d9GQxPrzbdufT9GgMPWgrwuaWSZ/Y02eJ3'
b'+L5nZp8rdQ+VaWkPaJucrfok6uTv42mog1yd+ijEP4kpx58ndG2SR/V0NNkfz976E/WiZ/'
b'X99DZ3/uoxF+AtjV1Nx8q8JEqDd7qhkZYwUmB/byYoqG7OuuvwX63cnibJH8XQa0Gt8yoO'
b'UlKJ9v0JT/Ho9fZKuWgX7i7/FYPwUQLU2skr9vdTKh0/19q9UBhOgHI0gSjz0QU8+WUGx/'
b'jwoFJTAgF5SXemIhmYEhH066cZUEfEE2yc8syEXyM3s9aIU//4yuEtXlZ6815DN87+83Jq'
b'fh3OdavsR3yDVyJNdSS8STlByRjPISnlz/szJfgWNp8VoGUoZiqH8/969RViOG35kMcOJs'
b'RBqibJwnP0fZCI9+gol2Y79l3IBnya9F8gvza5n8oip+mfxihVqVUD7tt0yJVwRchW+TX0'
b'ImZckvekjEGPeLSjJ0nV+iejSdJr9EMkMGEQvfVHGMioqq/cuFhbVI3lPWNnlvynaevPdl'
b'Os2T974coS++D+WIye77IGJuibgc0dG8j8uRnqKkTA0tHsrkPSv4rnuk69kyeY+yEBW2Tt'
b'6bQmvwGxUa4tGFBv3ofZQBSNjwqnMI8UiOgOmXJJep+5Y5AQCTQ8vkA3NolXzARD8tMvxK'
b'qc+TD37AX+buWwIAACXpGM1y0I048Nbwi+C8ioAS+eBzH7J9YK7Bw8aPCTPIE8pgaglRG5'
b'YR4KsW6t2HmysAy1oz/LxzmWlUD8Vx8JLgCPXzKWgAH3T/jXRhfPKVrJgYUlSXBcigutDv'
b'rXxSsEROTCkjCMiMz1JUDQCnajBhkaqxAhD1zwXoPeodVNIPkQ7Skj6yUDBImU/J3LmllR'
b'BtZiHJ0IWlo6x0IfrsahmsVlVtHvWMEcFdKTzwLroNeugP8WICa2u8mMDA9t3T2iWOn7rb'
b'd1w/LmCKbejjcDnoalzNLX7uzzutF1ULh3v1BrV031vx8pkQwqZz3VrhQjV6CCNKFtuGJc'
b'J+CXy7FQn0rh9c3zxhZTbfMqVtHSDFTRe+D0CUduDXzrX6WJH2vUThvn0GM8sNoOYxU+9B'
b'4iuSX+EZWf+rFMw0+TU0X/B111iUya+R0rwCHaldcwA3p7hzeLXr2/ywCsMccRkI8fevR1'
b'3P8+RXnf9Qtn49Gac1P3QmkOOSg+//ZnLS5L9DEsrkv6OQwBT3afKR7rPkY6R7LkD7bmCa'
b'fPS9XVHjW8Ya5MXHEEsFIhpVyFb9RzoBqXOyNrRvkMU8kKIiFJAj1s4QiJqjgL0dmCdIRt'
b'jbKlcLknFrTJFEPRoVbfIxyhXwJVf8tw8E/ut0hJ0uLx2tXMBryuQTczFPPq24YzeZYHqP'
b'/hJU5qh0Sir31ITU1FM1qcJRufFXOiozVOV5JpTa+zO8mXdJnoncxM4YUpElI+VdlimozL'
b'ssycu8SxQaKC81OltQXuqS6cu81IUJxUtdVKS81MWSlJe6oJyZl7poQOXisiUlLlekxOWc'
b'lJe6YPqmIvWMlJe6pNRTL3XJtE+91IWhvNQlZZl6qUtKPfWylCyHqZelNPF5WUrmxFRkYe'
b'yFl6Wgv0JykPlZSA4yzwrJQaa9EFmQPmll/ls3EYqw3r/0vsvHAPTJN8XSf0ceSgdKS0BB'
b'qAaLzH7YvvITvb/51OsBtYVubaNDutDSa0vIXJTlGzX9jDU6kmtiaN/2WOU8GTmDt7gzhf'
b'jR+jzSF2+AVgT05AxBbB9iCIUVzdcQ+zZy0SB5236vlk6Rov7JrLTOUYD9nyIAqkHUa4A7'
b'PJ7Ha3DwLn0JXJwZlszn5slndhbT5POaSiyGgM92wQ6p+yzFCzQUHDLsc8j/mSVirR49/+'
b'e4/6WnKHfnhpZCWCSfow1iOL+5+Tunw1AEiL07n6KNW8i6dbv3NT7d0LbgJ/WxCRQp8ymD'
b'Lmlkh4SJqNWgXJIfzwyh4n/WvTemB5+jcoAIesERk97PUEgee6OwNwtDnXrW1npqiPPrQC'
b'Gr5POxg47h1WhiCDtKH5Sxz6d4Z7EB4gsY4b12O7XkD+brIFSafGFxF8kXmY7M3bfkBwA/'
b'uUCxfJHJRY5vKfa5JcJEotGA1INSoxID3aoUIWCl6aPufNEj9RSk0vQXgfQ+llXAJOYsYJ'
b'KCmcKU2cAkwC7WlMm5NtUpAihpoTxKk4e0MnuYuW9xC0Cr9JiefPGThJX99Gofpn9fRpME'
b'iqknCVB0v4wnCegqvkSThBZ0PElg9mpIZwTy7EpTgYxab6wgmGQIGvGX6zXS1oNK1a3oUj'
b'cRZKWo7Cwr2SacF55I2T8Jy+QM03p6298PO+nAcnEgi6lN6jG9ntqMwRuBTb2bwIuEkPkI'
b'0mhNnVI0/i/jheQJMd8ikR7MG9bcJdb9WBvga+MTlJGfv2MY+hLNJCoPSFWfJv9goy6Tf4'
b'T22ST/UHUHU5N/RBOFDHS02gEHrsdpwIuKCuFG2yd18g9JHHi+rmFK90+KUSX/9KLWWfLP'
b'INLCEjJSQ+5/qipSk1QjBKZq/1RJqOvkn77q15Pkn5GIiFNEqpL/oRh18j8h6mXyPzqmBU'
b'gd0zz5n2ikz+Ges5tZm/xPFA8ClXjq5DfGM0t+k6506b6lwRPQpY6x5bcgVWuJkCFl8luo'
b'sSljuOpuVsC06K2hpY+YJr9hHqA714bI5Va3h+B9hqLl/+aLP7efvktZQSi9wzEtQOu6Xo'
b'GOhkfonL9FuYYsklzDt68wFOByuu+fdAbNHXbLYGJB3q4/n3e6LkNREfiWrzr5F8tpnvwr'
b'Mq8qQfsRZ5aIGVa1dN8y/K8ASJE5whVZ2s4myb/sonPVmC9ReBztS2aWJf+KWmAF+ub2RE'
b'3GDa23BW7VGoi+7XRa5gTGO2qLlKiO0vi7Gafl3Ih0kfxLazqzafKvqGgRsxQtv/2uVFMk'
b'tEmEvrFe33cYbXZoTzM06bVvLC1Zm+4rnM0mxJ8uv6+P6zPczWtLH/eXZ65RzA1/v0Z3qc'
b'C8BXi8yML5JAf9dYD2QwU4RNq0Gncx5hGooqbre2Zlb87D7NfHZ121VxFXBYhhVScUyb8f'
b'Xob98Dj8kNN+ay2G2Ln7FkvnlQN0vqcO03ZLlcPEENs7igySfPBipgJRZAsZiZO6vJxYQl'
b'Q4TEXWNwyxC41qq+SlZoghdqXRyBB5pjlict0kvkZAczefJoKH/T2qelpZyFKT1FFDRLoS'
b'KJx3LtkMXCRBYzUABm0XwJQ+Qi7nyAG9pgzuZrN+VnWsIuTqKPJB6aFQ9G7OTfMAB70Rgu'
b'iMSw0ZlidBmxaBWh4WF5G73fNw7FDvcq7srrvgAZE89v2EO/g/QOzCkvVsmtL4aGrIdII+'
b'yFqqe7K2xs6enFlFwJHZxFrJeDK11p+ezOyevCdzu7ftyantXjxZ2A7Ok6XdhPdkZbfaPV'
b'nbzVpPzqwpnCPzibVj82RqzdY8mdmNAk/mdg3Uk1NrU+bJwhqLebK000xPVnYm4snaWgZ6'
b'cma3Wh05ndiJmCdTa9LsycxO/T2Z22m/J6fWLsaThR2kPVnaGbsnK2vw5snaGo94cmZtTB'
b'xZTKwxkidTayDrycxaH3kyt1aWnpxao1VPFtZaxJOlHeg9Wdk9fk/WdlPUkzO73ebIcmKn'
b'qJ5M7Ua0JzOrLnsyp8WNSFVOSYpUZeEarSMpVS4FWlKqXNJbUqpc0ltSqlxCrihVLiFXlK'
b'qQoCpKlUvyK+ZVLsmvmFe5JL8yUknyKyOVJL8yUknyKyOVJL8yUkn51kYqyY2aUuVSvjWl'
b'mkrya0o1FZlrSjWV5NeUairJrynVVJJfU6qpJL+mVFNJb02pppLeGaWaSnpnlGoq6Z0ZqS'
b'S9MyOVpHdmpJL0zoxUkt6ZkUrSOzNSSXpnlGomCZxRqsInEADJXEhTglMhKVVRCEmpilJI'
b'SlVUQlKqohaSUhUzISlVMReSUhWNkEYqn8A0NVL5FKWmdU9WQpZ2DuDJyppoerK2xjmORM'
b'ai8ovMJmMLCcpkbCnJNxlbBZIRVT75NbpNBFUJaUL26a2NVEub3gy5nE1cg8y5MDxx4mO4'
b'JWHLrqhyVs6ynAsJ4UvXrkGyVpTlRMicZCrklGQmZEEyF7IkORWyIlkIyYjKUsgZycqRU9'
b'aKsqyFNELOhKQYbnAhyZDdeEGSQWVeyCmLsswyIRlUlgvJBGZTIRlyVgjJBGalkExgJkKm'
b'TGAmQnKYLjMRksN0mc2FNFKJzJmRaiGkkWoppJGqFdJIJQnkMF3mEyEpVS7p5TBd5pJeDt'
b'NlLunlMF3mkl4O02Uu6eUwXeaSXg7TZS7p5TBd5pJeDtNlLunNjVSSXo6t5VSE5NhaTkVI'
b'jq3lVITk2FpORUiOreVUhGTrK6ciJOt5ORUh2dzKqUjFwbScilSFEUOkKowYUgqFEUNKoT'
b'BiSCkURgwphcKIIaXAwbQsJIEcTMtCEsjBtCwkgZURw+dkwZ6qnE+FZFBVKySDqkshGdSs'
b'FpIJnHsxClOfq5mQTFEtjk19nqVCMkXNXEgGtfRCFqYElz6fUQ+ohXrHJUuhaLyQJRNYLH'
b'yRoZ2DXE6EpONlKmRJMhOyIhn8MqjlVMgZSRGDWVcsSyFTkpWQGclayJzkTEgjlSShMlI1'
b'QhqpFkIaqZZCGqkkvZWRymd7ySG+aCW97EWLVtLLIb5oJb0c4otW0sshvmglvRzii1bSyy'
b'G+aCW9HOKLVtLL/rloJb0c4otW0jszUkl60T+vmiyQBUmf/Ap97KqZBpJc6UUrdm7FaiIk'
b'xVilQlKMlU9ghQ5q1Ug3UnGYKJqpkExvE7imIpVCMqJGxOAwUTS1kIyoqYRkehsvVc1hom'
b'gyIVkKTSokS6HJhaRUi+CYUi2CYyPGTEgjhq8bdW7i9XWjnpqIVkIyooWXasZONXN+yzRD'
b'B5WlTicHiSLLUjdBK9McXVCWujlXmRY04p9kCyGnJJdCFiRbR7LRYSh3jvO0NCOsczydcS'
b'qUUWa/kcHqqldniiRanAG57Y/rp/Vh/UPOk7jraNoPifuwMsL5Sa+XRiBU76bYnKrGR5UR'
b'dK9iNp5V1MbDeF2IXTpvUlnfMwwz0PSHRyA7h61ogQ4M/517jTZE990mAhcER7ZUTNKNlS'
b'aqVP14pWkagSoxdP28PuOvybd5Fsjtevf42m/O2x9WKy5ByDoAR5Fd9+i6THxJMqldgN6s'
b'n7rT1iwGvrJpWVdx6uvWgNv1/tvalFIIJB9xRh6ngW0WM4LHYsQZeawt24olwu/WyGyR1a'
b'VtzzWYkVjZiDMK3bOfT5fjWnxxLA9w7GU10bxxRVjlmjuqECubCS8oqpDPmc3SP7hIeQqo'
b'SdHLFg2Vfdxu1/1xWe9+yDJqDu64PXsdfdx+DlY4bg+mXm6lHrR/6Y6n9WHzAxdWAqmdTR'
b'TuV2eN22BPjyw7qFbIHD48aWBK4Hm7PjxvL+ftGhWWRlHAuHaYcVWFn/fH9cNzdza2uJgt'
b'1FeoN5lHxnEiq7jmCiN6ml3DytfUxWSiyPLMuba+QRuZuOxsrDDRgg/DGY575m2NNnG4bN'
b'bns1/Eo2J1uJy+sjTDYm0A/VpfQHS/BzRcdoACfVmj2ML684TIsTv8kPFAwPploFgv0Uo9'
b's1Bwu0rJ/v7lBbm6qlcrfh6H9cO2OyGXqSSS/lPqTa2B4Yi+74nFwWQZnJ1ht3sT9xDyuO'
b'7UQiLbPpEAoJ8/PiAnuRJocpWdj9nbTNvZnJi50YF6RnSjQ2NpOXmNqnk8Dq/3w5n1fTa1'
b'5GZ92m6GV9oeUI/xkC1NXmQhkCtRXm8i2OWFgAt5c79zgS+ngriwl7kgLujlRBAf8jITyA'
b'S89AHbMGZ5IF0gs1mAfChUqD32uu2RGRDRuUNZb4i79ecioAzQoVlATZgOzgN8eXGYS+cW'
b'Jf2t+xM1hPocES/fJJBIlUq2Q9x+TMYrWARHB3r0qeH6gsclNQ6TFGeKjgJdKQYE//r2Q1'
b'bNWgUyKierT4zBJSqXmWfeCmSrxFQQqREuH02hzVJPbEyhFYG8PzHIeS0ISuJ+PQJ9zpUa'
b'GB5dHVhIcJL4yiMis0OMTmAKBWGdHvrebm5wr7HVQLRf5jjeTLjStHZogzj2LzRg4+zQEv'
b'5Yhmnx9gio0rxSh2mtYoxp1YLLJife8HZ65mgyF2q9456JjKRUDT3nBoY+B60yS0No0WAU'
b'gnVjUcuFIAuh0zYKo5ivrkq2pdPb/uU8mCFAdWZoIWcesEAV9/nHPuUcGYaTKfGgjwo5Bs'
b'5F6aFTkmrAI9vroeRptdPSQe0kvUNQ5y33B0OgnF5ervRRdPCXW9pihHttMQK1tgjGV2rk'
b'Wz9Icdk4ugqH2frWH9wM8o0KD4sxqCMTg4oWBlf33KPFjxoNoYDcYyT2RvKFIqOaTNxJkv'
b'FbyTq3tOSA4auKWk1In51aAb3gXivCS3KPbBz0doxaBRBVZhiD78N2ZprcRxeb5IaW8Qlu'
b'O+pyp/7PcwcnWyoKGGXLEoF2D+sLO4ospzO9RYhQaRriNdGaZKxLohMGNtYhZ8ajSvOM9E'
b'iXRM9qwG4/8r6YrYRzGnYY1DfCmhgZDsMQT2oWaJH3nc5HxqjtMljQ3dmur9xbU4LGQOuR'
b'FRQTdLYzCc4h0kCGiYUBg0JvSGjZobahJt9vdb1akvY1xhC6yjgg1BkC9nh7gZLsdVaS1g'
b'klvUMurHcPKDVzIh551B82eq4Ine6+V+YCTMEONdtXIJ6SNwBKCHVuQ6R0CAaHl6E/nKHv'
b'QEF1SjBn+YbNEcSzzW93pOfpNVd5xqzfscF5uKAYY106/d/4WqtuvuPO69dp+r850CH55P'
b'CWO8aipEU/G3jGo2ZmlnnsHs4em7vAjNvrzGnmN9g6a13Om57cFZm5u8Ch/Q7uH9kpZKXP'
b'geDMZd3pjG4kK9nySZrb98bpmireVbqCRyehEUeLOR270EyTLYdn9E0Zs09fU1SBHlBTsw'
b'JT4/toigdfwz1XNXrXP6ZI9aCrP7J20NUftMw70Gr+CLM8RIuy7oyWgnmrIey5yUnVBPL+'
b'TH4egH2/IZIpRPfCyqsfajV2fqHnNAC6klUWtrUTYiwVbeVoFeIE0Y4iSTRDRFko0MqiES'
b'1MnehGh8Gu0YAVZ6Ihq++tNBQNipF/E3fbJlGDRCTLCLGxNBFmC2weYVE8cRA2keju3frU'
b'sk7CVRvW8iVrLeQMaUpLycKWcriKWc4OJ43RzXCBwm55JXn95imKbu6wGzHk5GECcbCj/B'
b'yyiNlYjdzWuiCchiu5UEEvuh3A40W3A9KY/p251Jm5bxM/R3au9VtoQPCYtx+pss4Mdure'
b'TJfcJg/Uh/LkQVsKloDVOIY58YPc01fh2yuNxLXSaOmgNJLehWPeNcjDhoP3YaP00jrVuM'
b'v9icb8GkXkUC9TkPFysv0Lj0M+IMbh0a4lO0uwbFHZT11mCwu5KmIo9GZP3bGjEg3/Dfzr'
b'pVskQe6kW+JbriLEFOlhfBXhDJDoapklwr2D5F6OO472iMRdQdiYr3AFIenQucGdRNjUnn'
b'BpgQDGE5dV+dU/cXGHeZBb+vDoK9lyZRDdvtqJgYbd5nR+49JM5YLRdRNuotM/0PAetMIz'
b'a0j72mEIXT0cEOoHAZ27U9C3b1NckvPwzLkHJtxpbsjAn1YE/vfLFVeRE82xnm+YCxdkaC'
b'vpykR8+3LFBVnfv1yRWUUDa1bDbd9deEbKVA6/LpVVgWMGN2Gkwhj5KGeeEZbL5x6Kw2B1'
b'2w4ImlM4M8hO5h7xQG2BPjhxnobOA0yku/EQrhnPVSpKh4/S4OBxClwoQX4HjKR36GUUKM'
b'QRXbZx3/vL7ty/7N7Q2c0qh6FxgZo56mV34VrjrPD0AL1pZ+pWjs7dobxTnWMalw+MysMe'
b'daKYsnQo3DTRTTxblMnofJBrqkuFu74HjW3XUXkzDZk6/Xr3tcM8iOPAIrPQhnfW7whMLM'
b'Bp0tEiqUXkMBUx1Nbd5Z4TPvt1uvRnJ6yG3DIPbUoe9g/omUOXM0eTjHQ1+HJr6soRpNHH'
b'JdgdD+ZoywQjn/nc88TX+vjGbfJUIAk2dc64AqCciH5TWNqqmlTome12xXCZjnkOp1Dmsj'
b'buEdqTedxIceNLriBTkA4vEn2Ib1UuvEM/H574wNQS99JCqodtUwtFy0LOp78NT4szjVlu'
b'ndyFK9ngkqS75MxCds1HhxgxXHgNsRd0XZxDUJrD0/HCdJp1c75NMFyOnLA8Hc36E1Qo82'
b'DBAILG5o6YL3h5ETQqRzct78ChZuBoHsZmk7XkYs5rVNJA88Q7R09LLhcp2WmgM9JZoHPS'
b'eaCnpKdCm9irldA/89JRKhCWbnnhDNQeT77nAf1JIfQHngadSHDtJ15VzKHJ0Z952XJaBZ'
b'pnbUJmrHidoSlaSzLtqZA/GlLS+pOJS2T52fide/L9nPmaimgfjWcpg0+8b20i6fzEq1cm'
b'gWvTIdn2ycop2frpi0mHRPbpN1MqUohfTGQS+j9MaMwF9/QGFYtZIE/rw4m6voZQKR+pXR'
b'BDrRtN700ejeBoaTa75utdsTRmy2ba8gYehZvfcKADNvG+DEd7vsF3aqZCBdWL5Q9Pz08B'
b'QtbJJBTFcLx863p7FyZChALQnalWcGkGnqHpvXELM6ONvqGMOk4F/HJEIA9vzGDUwrejuV'
b'Ob+ZiSWrEvX9H0CMS9ZxmHj45VJNwaLafJJlLiSavFqBLkJtgIGNItTZnveImvaYmNl/ig'
b'RAEd2wtMErdyZsxAomUzjzxxDWSSTdy32bmZZClJtSJWGjosiJFW05+S3tX0x0S8CyuVFG'
b'5nl/ty+xlW9CIgrOk5eItA7f628XxnLGVGnLDyd8U/dU88Nek46Zgz8un5AXVAf+z/EFdT'
b'BY4C8CxoB3sBZwocuXesOH2VAkfuHctu7Qtaa3Tkw/Mu9xflo9HoyIfjxTlXKnDk3rO2ps'
b'o6cKLAkXvHYqfUCVgocOTesOImMJ8D00P/dGUBbQbisfP6MNpCmi4CJ8IOvApuZprn8SnI'
b'Pa8sYPrFCMRM4+XQcZdFjvKYQX5aQ+r7nb8/lfWIy2/XRgrzWwy9KrQcO5DetbnJ0X5b4+'
b'LIecP10or1rvZv0XN5RG1Sc1vb54tJ05NPUymUU5RXBLSOsiCAGLnayKNBlaLd8ovJGLMx'
b'GzATzsux33ujBJNJPmFcf8k4OiqMnpWGNWHC1c4MWtl9GBzQImShAFGpy+vR/MOqQG6J0W'
b'3kRP3l9XAedeOG9h23IXQP6oDQhRog9JGYtW3GFb2pIfpmIxP3Ajm6ifYxskSxM0vpWD0S'
b'oiWid6YaQ8tiMOqbfQrm1L2szdJU2GVtrni06zFjmmOqvSrUpo6bOFwQQZPvtn1oOktDh9'
b'EDFUPfQoJS0XtHC7LROYjZTeNosbspCdg9pKn9lCsDa8Z1GPbIVsiLn8sJXcHhsrfrbiEr'
b'V8j/jvdkZxjr40yuEpXHhtBZ7ICQwwTcZhE+MR6/nblD5E/rFyPMnQacJrLXwxMFjogmgS'
b'i6cOZvXifx1RNoklUS3TzhWvpUUNc8gk9pzAGK5NSFxNh1qZA+nwc3OYfaven5JhtEW1Xu'
b'm3P5zDL4wpLdxs0y6NGb6D7EAmE9n7ZmUayYwUO0P4HqEJYqobFtwj30aEPRHBhJPchmBg'
b'guomzWfokE3cKAmuW3MsjXCURb01sZC9I7M82fMA/Nt55I5g6LZpLeoVquE89iCuBD1tNF'
b'Ojo8UUdF9R7U3iBrd1h4zJazQLryrBLfgl2J5wEYFKISt2IkGGxOvDgtzVNP/c4rUluh7G'
b'KZq80mQ8/OwGJRkOCavCzzoHMyK/Fvw8YqNMYSO8ZEvzOc1wMS8qyP2LaCurUCRCOqPLzo'
b'HEMSzuveLNMii8LSPOTQS/MctvTSPCU3r2kgT75ZzYCNnpQcTS5J2CXgOZ3ffmcjJUdXYz'
b'qNVj+LVcIGARE6OWo+w/eReciTJJ1abIdbveS6SDq5ox7+7fq6X29fekCvtQt4ZchRXHG0'
b'NYfhuhbV4Hv0uAeD1UutTM3D9i2+Z6GuAMrgObVEOM0914C8+LHSqIyxM43q2zErzZAXP1'
b'KNRtde5pojb3tQelVCEFUfuwbX5zGk02eskTPuSY8q6aInPSwtR+Mhf6f3+hFOd2WHAz/6'
b'3Q/0XJ1YuNf4VsUK/1H2w2u0No/y0YZX8B2dwYfckY07gnOrBnltP8MI74BQKdvWIlK0jD'
b'0AbkeLSw52jSGrZql14HKxdAF0mEj7MKpUMN+2MdoIxAa+YXufWUzlhRdH5aSPYIs+4yoh'
b'XFT/th0uyJfMQzS1sdY3HFMbi2KwGpD/L9verRzkWeZSKl1+NqldGNECqcNUh+/z1Seucp'
b'FIyuqVAE59Wjkv/m6sykUu/V02qZwTbwBNcnwWgL5u3DqCzNVmeHUgI+N+1MHn4YBc1JcO'
b'GNCf/AehX4nJkbBdt7frlFArOvNkTKgrc4dIRrQekDLOHCIJp59d/8JGl9Go3FMyscky1o'
b'KgA+SekLdoKo/IWzTIAP0WTY6+db8xygiXK+23njmhgkZ6Bf2/cAA4je/gaMg5v506kwVw'
b'F1myQzY9YmA21x18vLn71vFmxG5dNEfH5g2chh86CkY5ehSH0PhOeRTOwSbHPGHZhRdy0M'
b'qGUMKIyN5OmzFp/HzYDSe7WDa3QHgzBoN+DInboo0ZXiFGBvjKMJ/g21+0hVl+F99qhUmC'
b'NbZEP+U+o2bnMNGpSkerBrMg1H/FvP3AdGclivWo8w5+dC5PIZFOXB1I7Qox671IjuK3n/'
b'xBBnLpLatzfjh9oi5JDEffQUIrtfTVoG0cegF2w/DCq9nmBKkbnpWk7D2vDHArh+mWP8ai'
b'1VgGfTZG+xseX6BcSttCZtoZVsUPNRzVpKXU4Ms8VbRCXsqtL0v3LUM8cuaM2M/rxwH9jE'
b'wMOXYoPFpvCbwb0LVLP/9bIu6LVG/WAHkVqbtlB1sp2BeExrTeBPzPB7PSxwVT+637hoXD'
b'7JpqLiTNuyfcSgu03KnvwWhS4UE5P0MAUzXaDpgeEbMvO3dlf6reeFoZyla8mXGjH3yaEb'
b'AqdNrMk0dqqmXyKKsNLb7VUGBoBHDYdj1XhyYz0OetWoVrLRCtwjksWmtrkke9PlMnj0F1'
b'LJLH6MWpVfKobF7R2B4jbQjN6XFsBLvMiI1XyJc50dEKOTTVR730gNgxdlASHvt+fMRMZc'
b'Lfnh8I4HHHD3gyAITpHyPVBtqIg0SzyQSRQQ8y0xq080MBnex2GMeHP63JoCVpw2jNF036'
b'nteP9iCwp8Ia+hgLy+iBE5ZVAxYWkud2sThmKC8xWxZ753ZFN8JHvhx33+3tyWRPBWcOO1'
b'wO9nSyp4ILh7109giyI4LxuIP4ikxvzyEHOrgiejydzRVMqB7diToTpvmPPeS2Vlck4kfL'
b'GLRRy/PCfAUd09JKV24MEOrCVNE3NOW6NXyvKFvfVkeF7pMWSwNo7bdxSFB+LRLrvoXDgu'
b'prkVs6rhVRq7jWbTTUWkgruBYRta62pKi3C0977da6Fx3PxqqHauvAq7agTDtDu+DBMvMm'
b'Eb4jlQxtKBwhxFThcXgUexl2GsOjX/eBqvAIXXAv7CnZR3alvM474XPYLN+p+Qr5aGlVvn'
b'MDhPLNFX2rfJeG78vX+tbF6ZFQnBaJi3PqsFCcFrlVnFYiXZzWbVScFrq1BFoZji5o61YK'
b'2joIBd142he0dS8FbeXRBW0dxH3mUjDpNNMASa9ZWMzVERfQdtSaIZEomAjkuH7g3jFP9k'
b'xJHR449ucJTxFiKvukTeRI+gOFBb69tRzxcLZ5viIZL9NjaH3iod5owGlmU6LxgNPMGLI2'
b'vasMHSzvSGs1bgFaq3Ck7UuHTW4/dwjJKRCYMDlQ3cHfTgDF7x82iZ5DTJYg/VITkifqA2'
b'RRzyEi5DBMl5YIzyEijNFziHDvnkNMzVfggI72CuBSL2EUGWiV5ob0sOcOV3QIq2A4x45v'
b'ZjDkoAAuHC7IKnfI/vLHRu3CzpbEUVl5kpCXpq5II8A33nkeB9oGVggXRQzt162BY0r3FB'
b'ld1qT1M49VZhBXsQxb1wUHhMpgAH1/wNwCoxsEWote3SGwsvhY50F9+N5bkwVZ10+KMWE3'
b'3ppE/m/D5tTcUFphJGInfiXjVE8UIkC9uQAt8UlvLsxJa12a1brfdzt7A4v5DNpPBATVx8'
b'FBiwAQbzsg0N1wxvRBXq6QK0NbzzqdOfHK2JgDoF6/gDKnGO6s7ERjaqLG/L1mOE/pLZ5u'
b'x5EIXtRsnl7DKso5Uh3e+ITbaBRFC9d7IOhVn/QeSANautOM38G0EI3syOsl7eJPlfjlSx'
b'Y1P/WyfpnojWLnwN+c6UhfjXJLhpszWwtEcjs/6jZNIh2NLjmUt57wXQWUIo0MR25vAF82'
b'Ho+GSPE/HGUJgcms8sBwIVSVQF9VfILKAgUkkEO0mIc+hUdSwdEbFgWScuEEYD/4syDzJk'
b'De5qux2Kk/PLlz5pN8FiC3OUo7zye9/dEw9ON6HzaY2Mu8hf3xWcL5O6b129uPrs7IiA0q'
b'UHV1v9fQyU177jwJJ0bpSN91a+lwoy5pddhxSXJkBpIRG/d689ygYf9nRXrUB86nAPuz2m'
b'WbJ9vIgmmlaL1MUtPhDrqkXs2ncLymRKRNLRBbqWTpnTFLCSw9K7bcheXGE2vLahXr2mNj'
b'udFFKKlgz+vTcRQeqlnEvQ7Spep0eb6MWAVznja9ZqJ65MoKM/Tqyd0pM+v4MgzmEoP79f'
b'HenJtvFh62p448vqBIoSbSs7L+ajJFm5udIiTLr5DHMRJs3zR6cJcd3OJRGLTi20zUie6K'
b'I3NqU9sFSO+voKy+gvLpFRQiiOCx0BHzSuqIG4vtWN7eq0kVbS7MipBsOkbyyRgJYWt0LL'
b'DmXcmrmbG44LhHnKtEb4NN0K7iN53RItSbzuhOgvZaWSK86VwkW/2mM/jRm865oSVkuO7s'
b'bW+8UOXMfaTCfkZ2/AoTGw6I3wXNZSpUUFuIbW90sHoVrCIpeo3xYbtG7W3VzCvNOb8O0v'
b'9h7rkdL5tZ7Dv3LTXzIuaOj4I3cyOG741HgtSaJxE2Bg2H6Iwr11OPApgplvhHNwI5OhRc'
b'6DUqBqpP4tWKjjryJRmXc3Rve14CPIjWyvw7XtQwwVHJ2rGSpSxFQXpPpf3Ur6Ch+Prucn'
b'2uqHH46PCMg8cncpYWDidyWguMTuTQmc5V9EvRCXVNRxnCaK2hK/Q+85lOFZGlmtgoIrRO'
b'B4zbuoOvmrnD4xYOMLrmH/kZ6X4oUH2mpcKgAR32xS0MsNlHJ5RJ6+RrOko+ctPZ7VIX4W'
b'c6U0RWKiLPFBFEd8A4+Q6+Sr7D4+QTPAzP24s3VMoomNvQ9zrzzEAPmnjhQgAUsG+xnWdq'
b'mHL4SLMysoJd/ZS0fop+ZuhvA482ObPLgpA7lclqOpxPL7x5ydxdwYIxN1fw0NRW5g3oPH'
b'VbQHHJPSjsIqNjtKT7Xl1klcN3dLC2UHRUfOgMoseFsuUyQlxmQeivXE9EOG8vW+508mpC'
b'+62tuzw/2ojxDkWpzz2gdspKh/EdrYzHXXrq07OkFxOgJb+VlrRK1KWEdZVoe42MpFucga'
b'C9vB+FcMOAVid9bHDTJvpdlKJMem3lAmH86qExRnIB5Vm9CpzH/tgFRpOoBUea3GJW0PmF'
b'x3yluWQLZx5xkCsqUIwpmsnNY5oSlhFqjorlPC8zRs2sZ7WC6hlxuO1/vuzMoRERo4rdHL'
b'm3EuTINdfkiCypRikzzxmjwp9CypcR/8+Hbse5ogQ9i/iP3GHFbNL7xqxVczHgHh54c4j4'
b'Lm/yJfIR+yhiZVFxbddfg8BZxIH+HbIhysieBxj9syMsgKiwduiOjkHO+oon8cUsFFmILy'
b'oU9kvCiRLGYf+B9uHCnsXsc8gSdJaaNYQqkEU18bDehyyJ0u0WnHOaSWiYx+9CgqNoMPI+'
b'SI2Z5jHrBVolaoRENovZJ24hBFHicJXpFVId5eSpe+A5JhFoFjN3jyJPlIzT8NB35zeJLx'
b'LW9nN8kjNGu6jSRfXgdB4enoWVxqzLJkQUVcjTJbTMOC72o191+1po9itXVKRAY9YwbIQT'
b'Nbpv3XFgolRtM1Um9G0q01ljAkNVGVaYkNuqxiAtAVeJMbKGoJSwFDUwjKzWFIQSKovDVS'
b'C9bVOmMG2KyjJRlpLI7KsnmKCiRvfZshw7jo9jpdTjI6XUwWOltLJwUEodMFJKgYp9I7JC'
b'2zeSpcwlQeqVYeR0ZNSJeq4HS7QJPdCxt5Hs5LeOyNIhJtJXhpkowSuzOmRnP35Wj+345r'
b'27E417E5II1DYkYPxOC2y0Q73+PU1uqujQ5ftgzAI/5ua5bIkc3V3ewgEL0GIgx6Hg+l3E'
b'PDH3dQ7Hm3d1FoY9euIKVS/Sw5EBB/RB3vwPXfbB7IHxfH+KJnXQL7WVkEIdDQrU/cBDBD'
b'zFkQbsHNP2CppCaC7Jw8EkAIo+ome0e35ZRhHPfbgVlUF89Rez8BYWkGLAvqTrr7zPqQu3'
b'OfX6ofgCIonhHJviYE2iZuZLve+4mEeIt45i9wDYbNhR+7X+xHYKAYrSjApw1JWVJX9l4p'
b'U7TNecMRaZeCHBp9N2rfd8IalsJRi+0mTRNXklQEU7U7A+UkDYvRPJjI8svtgjRzccwsFF'
b'q8CoL7eeS1slV20p15heQAb+bdufT5H5RuFBOaymmFXyO1XzefJ7dHdKClrt4i1A+i07fu'
b'sdO0uHDTvQ2tZ6kvzu9fUVv0Vfn1lCFqDQGf+OJno6df5MA3L5d3cMQ8qnWCXxBlYNutuH'
b'tdmFoUdXArYGvLoTcGXg8bo4pFQLTTNGsB2dSWuS36NdziVpn0GG0DnkgJBFBOKrWxAgWk'
b'3Oo/6/Rz0MCkYaBDJIzyKzhNeEolfByLA+bZ/7yPIyJRwkLEC6ATQnS3fjc9A3nyFsDMOm'
b'igE82mcXnpUtABpgZIbVJDcssAw4MlBjpMogyzi5slcz6HjvdkEwvttwCUjneGHokOGkda'
b'/BcMfmwVNguhdpFB0NQCUYLy+m15vbz/i+RlRzoG/dcDnsoQfsZbSqUmG8cNXqJaxj1dPA'
b'Iif4qYVxOq2hU8TcGbjH4dirDp55cdr2mzUm/EMop4mGUcF69kz2CunYzag3XTHvwjVZlF'
b'PvoxST5GrrxBTH9Q76KmGwLAYMtztjjnR8jnKWYX33kiI0o2e92N0mz9EFXjPSzmqD32K1'
b'gYnvc+h2UGSxkQbZSnGEGvIcm1dOCai9SZRiZJqh6Sg5kCK+8BM5cGWQvEJ1Ys057NaHDR'
b'OaQoF7jnqXkrQeKQoCvmEarq78Dgi13wBqH7E19Ggj0Tq62kmsDDzuIimhthmlq2AFMTOU'
b'toIggor7fL38WwtnpGsLY6xtzz0j6NuNh0YaN50Oz1u5uhHTWQMMcqtUYYHL2p8pmeQWeQ'
b'2epkT2Fzl1wtjsNVMzpgv647O+uYoZqcw8UDsiZR61OFJzNR3VHuRpfxzGG9WFQfddd9YH'
b'JFnEgAMNmXt0Gs/j/C5bzxhllcfH7icOl8zm6GGQUQDe4akfTsExcjMertF565VtDPrP6m'
b'QrCn18xxNSFg2IyP3rO55QrpENR05aPa8A4ZBkKdHUkKEF54qOygAVaECXE/IV2TSgw1cp'
b'qhkYk3s685KA48Y9U466vSJnOPhDxxwqZSwv+R0SgIhOehLHruIc5CflF4yhzDzrBeMpmH'
b'p5eK7pKDXI3a8SZgPqNVBtwmMm5SLZaSuGDKSzB4SWsBPDBeJa77R0mCeRfjat4m09eJPT'
b'IuHhgKvnT1YLj3/vnZNVfe1ivPfWrqrI0Y1XT1bzaxfXwcy8o2tW41nfe/kEffmVi+tgbD'
b'7IYDkleb8x+kTjvsUwZmYQljsfuDKfQdeKgKBtOTjoVh7wV7Is7L0rAZQbchzrztyMM+ar'
b'AG+6GvPJGil9LbHrYWaxMEVzpf6tiN7Q3BcLE/jzrZBMhhlptuOsX65YL8f6fjuxYHdDsG'
b'Vde+ZVRAvPuTW1WK7uEPL0zkwnnLtb46tyx5iOT2I7X7RIvd3mnyF3UFuN1RRi1UoQSK/0'
b'5MhcpfSQI0pPY4n4lHG+BBqrQvBk7VWhCu60vaqjxWsVSLGsy1Eo3aO9clpf9jY38PiYO5'
b'JL67EJDwXxS8zGpoEcjt6gLcuWc4NHNmrW59hALXNo8AuV3UDaOs1CsovFWM3xIYyQvDTR'
b'XaCAGKK9QzpAtqH3tS877+Ij4CwermWxfsbjHgC+Xo+RaBe60ZyE7kcJ6NER5aacI7rd1w'
b'FKb/+gTPLTgHo7ewXdWFFo8xts7xU8axbr1jEyzC+jU4dTJDGMrEukZ3jYcqvJ7dSCPTxR'
b'gbcXimWVpw+DMeNbKFpsNDPeqetwc/VYhuox7MJlnxk6zYF7rJMUw6q/QMfsRZmrdVbttE'
b'3ie3UyT/OIEeKAE5Tc8A35YM65oD7JaAwh3QML6RT+/NXlPFm706tBiOMsl3Qgl/1TTBlq'
b'01XJsPLEBTMJyK1yyZLvFgtYf4ZMzxMeuENF3Os7WtrEL3hSB7Df+p7n1GFuF3jqyGBlun'
b'RIdPVuTtAtHDBUfwkMY9N3wFg6XAFDmkq9Ots4nwoW3yNlcLUFTr/cskOn8UrjPNN/MKdX'
b'Nab2Me8oB8LBnGqm1zsaDYZb550Xpq/vnuNYUHQe1eHXjYV9yLUlx2HWc+LQfrh+oPGpwv'
b'1rGyyV/rzuMQnRTmcB9rFVBsJQG4u6CnAka+tw733m6Ctpl4aBrirO6CzAUR6nDvfhzh19'
b'lbMTMt7W+0HyqwSiDRlaRUeGDEyTPYFIKQ6nN22jwXz4Q60dNQzmePKu0fO7WU+oYAwvrB'
b'SgyPUYivDC3VhLlFEYN1ENRtMRVD9tFjdNDe07bKj4e70aCZ13f7UaiXZ+Q6FoW+t3rJ1M'
b'HXqtgSzTwBo/SsKqOZojovfb63WMmt77b7HlGLJSr220qaJ1CbF22NOM9LEPOqkig0ZqwK'
b'AektSjZsU0cikoFFjhkOfuEWNLwMsIj3sRz4tRhOSs0iokRs/MkQQz0qlrgaKdgsLwzajV'
b'oI5wKe9q+SJz+GjxwsHjyfQ0iRcEWXsIvKCK62lzNfF4NMV23uMlQOgrBo0CwPRxHxnAkd'
b'YtT9NRuTLmg7mB2iQCn9pcynF9A6FxhgHcTUWVpdwV1hg8SdLoE17xfezvI0tDdh0AA40u'
b'iqP8rnuS2S6zQi0QIL5xi0QskX6Can61QDBDevUCQZ2RVgsEKAi9IsAmenNFgMPFEORZQp'
b'5hL7oPQ6FGE4SrIkRJjfYp2of5DiwMMiEEqIR7rYEgIcF0DMSFtRM19ZL6D9XRIRWXh23Q'
b'g6HLEXDHNkpk/+UxuEZnd/Fr2I0hAg+ZqtccapSKXnNoNR3lF7LkosqPArob0CcT1peLOs'
b'FK6Q7KQp1FSyBu0ARPToE09sRzDZiLBkqTUGCP6BXttd18IM1A3Pt78RgzUOU180utkKBw'
b'L2qJBFnydd89hfzFFHevnCM1rzEfwSv/y4SqGdrrQWttNUlM2cwBooNfbZlO8e1VLTrRqp'
b'alg6pFWp/2mCeH6ByHpqNhtgBDnr9krDMAodDTRN/kMmlA2lYGBXOSHPzEE2PNIUw8MciH'
b'c63LpSXiiSc0skM88aSnaFgtDC0ekDPRbYkINroeUdNRCiFa9wr1/w+rTtuH0A+q0kOU6A'
b'TsjLRfWjeEXlp3QFhaJ4Aey+toLEK9TZwn5hYae4SJo8VhPJus4ITGIlcLtSuHj8YAB8fv'
b'EuSFR+MwUgvHJtN5adEATC0wHoXK2uORBC7Q2GllwXP/3F3OAWZUutyQ29EFipqOyo0ezX'
b'qJ1p+Z/Q71GiUKntO/Cc998SucGbe0ml2tDBCOXNeKvnWJV2b4fgJmfeuj6x4JR9ctEh9d'
b'nzksHF23yK2j61YifXTduo3WPCykD6hbRA6oLywpZ8YnnvYH1K17OaBuY9UH1K2D+L6yTD'
b'A5oF4GSCKbW8ztlCAgsxoCkeLVEDjTW2B5IKPBA6ULXcDMPqgXcCkMvadeIWGPFY3+4KsR'
b'BfFEnW1O2nerhtD9qgNCx0oguEdU0WWZiCq6LFPTUWWmxwOGr/UzzcRVD8prWP0NDTlJ34'
b'+wlIdB7aiWydUDg21rwaftBUKK02au0NEZ/ZVh3TqGUt2ZsyRkX/MMfGsZdpkF1tUMpDG8'
b'8XSmduiNwIrAugqsNbzrRxahmGDU57MA6/5ApWbCRJzVlWwzRfPVJY/4dUAWw1mpSCtFHw'
b'ZZL8TkIcL90VcTWL8xj/nZAJknZ69itZ7QQZkoeX3wbtcZU7DSAEdeO2kujK2Ni9Pl3t6p'
b'Vk8tidERKiSB1AJs1NYF8+5VT6kQpOiXkFEpOfCrGzvS619vXYF1ofKHTI2uD0WeRteHaj'
b'qq6RUZZ72DtLCIX8J0pF7zFChsHxHa37PHejKHE3JFR4cRNEMeIlkl9mIPax3lFFrMMRVq'
b'3k0UVmFZAxf8kG/mDh5otPiQee1UkcHsxIDhch2QSh1EqEr5Q2t403pGS9rrGYbQeoYDgp'
b'7RJgN1x1Uy+BMU6DSHsOucLZPhfn082jlT4Qlt7jjz4C3j2QbMIByC1iZcZLrjF1NIEF3D'
b'mqYe0PILeGUFOrviaFNQw3WHOzJ8ix7ZWkIOd6ymGvALlMtUo0qBXM40w9+JuMw1qk1s0R'
b'cN1/emYr6iTSFzCMXr4p3KXqSGlAMmKBGfR4hHGTWvykDqMkDo2oAZ/k2w8Kyun5wn3vqS'
b'B/ftt5uc18ng7YtXyDxdHggjMmlB8vQOMgKNDIxXpI8shXlqPyWHG0srQdvcQpKrS0tH+e'
b'lC9DnZMtjoqJLJPl7EjFF4uLI+hne9wz1Pbm/XI1khp5CdegkQgos9MNTGIb4wk7kcX5hJ'
b'efbeomWCb8zsaNY6s58pH+Yt7bfet08tZOxb5SrIqrLocUAfoq0vG4ufoebqmlUtHe7MYq'
b'FaDHtVnkvK09vEcJbpCHG+AKKVIriwSnKaRO+IG1KpyBXpoCFPAnnrbqc52V4/Nl5RKzpo'
b'bOgbzIMqU2L2Ni9e5tWQfOx5YzbvW1+Q1Ap1ZYGgTxsgVqdTC+14UR+GqSFWrQ33lmZtUq'
b'IVa+My0qsNcutGKJMKrW8bl6JuG3a4Dqp2pFe2jWN36pEym1SL7m3kCjadk2ZGwKvPqSX6'
b'Iy+jZA0Vw2v215aQOt0uCakhg+6vTPvpz91tCsFFQ0BRAhWrcGiWNO2iAXmeoVEdN49GXz'
b'OViI6Pm/369HDZWaQhct5SIKPgpKhv+n7PNHP01WgAj/5h81XtvuUCKoYyNveeOUz3BmMs'
b'WsRFgq0xRRRsWFBboQj0mQboQ4PoQ4X79r0E+w0DqIPybFyRWTdKzT3mwXXPVqh4t3KexE'
b'9+TAoBwn7lLGD3u9f11zeCCwE90hjk9DAcO7v3N9w6lNEo2Oe/xvQ43CQvfLZskrys1/uX'
b'oDzWBuFZrmATlcGxnmPNQfpetcC3nz4Rf+rMzZ9ZigGBlLnyAoP7SzQPMy7VNIy0XsxOQf'
b'dva0wH/CZUxuD0+jaduLPAxkh/9DTNlOzhYRvZQS+YuNFCPMNFxOxOWNHLRKvtTN2xO7gL'
b'ajD+Chkf3V/mbWCZ94XRWAWwbxgvAqD7KeUuUnxVXKL3zhSmFHwVhH0BuQmAvnjZpcbfrZ'
b'PNFD1Oz0rx7IPJtULsWZVKITpJrcKjNOkIJVFzDapU6VDse8ulQnS6DM6Z5qZ/NPO/DMCp'
b'Cyf2Tbmfolt1KUpYkCfl7l+p7GeaamKjiGytiLBF6YDxqXgHX52Kd3h8Kp7gN+UKutmLXp'
b'9FQoPCjBLSC6rQhuzNoaj50Qk4uAuXcUynQoVJDrHuW9ilyVF/rN3b2GUORjAzZhHFhxzm'
b'ib6wlOGOzlUYKceLE01RGzS0fxPO6FJB1v7ozgs6unnB25yRxMcHKOnRPVDMVm2JoHXMPR'
b'TVV3EoRkTGHRUBBNO6b612zxxmhwKqhtxZtFg0aqUO1KfxvcNIBh+LtJfMA2rPqDbYCTUF'
b'kphZrzNINY4x8G/6B75NisYxN4milcDJ2O9gYAJw4r3XGe/OflFL50ht9EZQQ9r39obQnb'
b'oDQq9OwLw5XPLD6NNF4s5FXO2zzoUz2mkVxnjte5GMz1hg9HbQaEXbOPUn0qqa1OEsdhe5'
b'iSI+4mEktTbgc/P5El4qxlzdABeZnKeMYDiteX++N8eASvpiUs9fyHSV4tzho/Q6OF7/r0'
b'qPxnlQWHhkwV1lSbyFPHXAKFucbzMgjkKYKpaEosDRPkDlgjoz+8+hRDAvsvjIOROpGzxD'
b'1m2b9KhAmAOvR93YEAj3odEUG/OljQ9XBgnb2IWh7c73hCc6DGk3tUtHqFZnA5Rmn1lSjU'
b'6oMtoD5o8vymYONSy6ngX1cuAhzcNTD83sT6pI/rIkSqp5HLSFt4h5ZuQTZhszLy/CYXQ6'
b'N0m/iAFfisTpJ6ehvAf60R6OZ+WVuQPch5VLphyasbnkz8wfUgqiHrKbWSpY/vFS6ZfjsL'
b'k8mOXaFYnfeXz1q7lFxTC5+N9t/G7BgtBLtzOWgjQkNeQxLJdmgoQF0txgmIPYY7F5pWg7'
b'aUE2nEyLrPmhpwQpgV3/nWcOUT/U6ipyJrrNBfFEd7eAVmuEqMhqjXCe/EGtO03+kKM0Nb'
b'/3ygCGgDp9l5EcGVmXxK4MjSui46N0DM1f1ea/00lErSPqQVNZFVEzTeW5pjidClRQaTwy'
b'1os8/gfPlX0H/l/9XGlUETfWq4T1PT/Xzo+Hjtc6KI1xlfyhl0xRhqKLtZPkD2eCNMdn1D'
b'HA3cBTlRjd8REUMUUGNcWA0X2AbWVfe43woGKNuP5+O4unMT7yZbkBM6S7Gsu6mAo08moZ'
b'7rCBhWYCjdwaRpyaSqCRW8OQ+mqxOmAj15bj33y1WBOwkWvDifOnFGjk1jLc9f8Wmgg0cm'
b'sY/p1XCxUCjdyCIZ3qInG10Ru5IKN8Wiis+U5rTWWFpvJUU6H2emTcejx+1Qg8I24ERHmR'
b'j7E2xiTCU9IzpRoL74G0gronQJpVhPjnPRQs2zTBb7RwF1x6z0YeZwuE4T8T6n59Mq+wto'
b'K4W2PThSDRQB+8mlGLw2EbQzKQ5XxJ3bP8zbMe8tHUgVQjYNpY+BbkA5op+mBNdQxgLrr1'
b'6ZorjEtBWaWBKGVVwvVGqILH6Nz/ArTavZuA9NsbRSKbPjnxjdvwRKyOsCsZxt3IDK4dYc'
b'oQbkVWIJcJp2asYqtETdIcrfcNJ0l8NwdpbaI2A61N1DQdWRkgK9ZmQxBjo1nCVIu/KXjO'
b'SvSayRj3J7tTQuNOcx8ElYsy0W8spSD9rhamqcdgK4X5bnhLoUVcsVUU2WpHCYPKMZrTzw'
b'zt92GKJpByJqdAfnaYQ/L5J6PQQd9qCKGwgsJUChIUJsTdPfGBHTtPZRE6mpsALOg6IGZL'
b'YFVi0n1UKwB5asmgk08IjA4eM2BdbgvSb52x49UH5fL0btWucvxTt3fm3NwxMlVeKDoqXw'
b'plTrcZiU/b8bBq0Xhcre3IGTNCfz1my8hR27EzZoz8OXYALe0H19qOoYKNfDuOH15rO4oK'
b'NnJtOXGyqoCNXFtOGGJrO5AGcOTesWSQre1QGsCRe8uKM6sM2Mi14/iBtrbjqWAj15YjQ2'
b'1tR1TBRq7JsZ2tXezPeIsdoF6pdJUFaBS7VuVlcXWoyRxeOvIFHW9o3gZSXUNfoQfTCyaY'
b'eB3DoXkSA6cfKT9sOEv7GYyhGw3ou0AKMkbXUJiAzv0Dfbi5LATDfHt3tdiQOny02ODg8b'
b'JCbuHRTawTi46Pi881HBsNzhxL3DogNpJnf0X0yjxx4fFo1cIJN178gU5g8WjlI18oNA7d'
b'xRofZ19acLyOkbt8HZs/urQj5cd+ZIVZMiiurJuh2uyZ2bXs0THJmYOPvXfJgVCvjtSMRX'
b'eEmo46QjTXnlZ0PEvJL23ZXxjE7UVZNv06y1UTZ0C0RjeLOFr0RcQJa57ZMheO223ImjaG'
b'9Lm1WczSAWVkxbYCKQM/RydfMMs6aqPBAqlx5wzYqBZChYaGHIjmaYgoOj+A0ovOC2g6yn'
b'NUI4giJwQgnOj48KOVreWCtNewUhL6Cg1y9bVEqaFH9xIxyOsTopOA+u16BekteAXf2kKc'
b'3mD7rcRbPL2lCL7edoX4Z3/KdoZoQ9bPPKH7N/iOzh8gW6PzB5qO8h+hIRij+yjNLbNonL'
b'xVTrTnq90l+2Y53InIrw93NskoTycB0TfuBfRWjubJdzP0BkvnZ55wqbLCj1bY6+QkCnvj'
b'vrXOWBYAN0GnMqSrcvS7iZWzZk5svJbUMOTNaC2pWQDU+nlt6KCfk9Z3dDBqfQmHpiOrHs'
b'YGfRn/b4cLYnzbdq9rA+3DyX4Kuu+ejZaTuu+wnBIjQfXzeNAOiGBK5Btsnlna22RMHb/f'
b'8/+dXCmC6h/wS3hmLbfw3gfnaE9ODCmBW7Lv9enM0mHeS2Fp7cRB3oUVRc592hRcuk57qT'
b'3oPVUO0I485t1YUWRfxIUh9Cw56VkPSD/rKVP3HVVFBK+mQitQ29c1LVNm9lNf3OmgG2Zz'
b'y8ay/PO6qAhhSpVZQu6Yg5Z1iuZYGcWMpEoN7YcK6DpCRs7grUP13u30SIUm0D0Mdt8sd9'
b'+jx9nmib+bccL9tFPXqaetckOPmmBmwKs2aN2OGyHK3j9iUdrPNNfEoyKyB0WEebYDxgtE'
b'Dr5aH3K43j3PkhuPVtBdtBu8JKD6A5RjdK2WpqP+oAVj3z8MO7v41AQyrD4pMFosUrhsmU'
b'4N9nXoURs5TjgBZosbeDS2oMp2+m7NLEtGpjEspK/mgnU2MH6GTWUHqHF6aZFggFdq4NYZ'
b'lYl14Ed1F4B6QLO1iB7jlx4KhnYOik3tKg8G+zoH3bKwc6JqQw/nOsp/h2lzOgeJQd3c0W'
b'JS1wrgjeqcFzGjc5HrHTjnJD7EMgmgnGKZKkyOsdQOdIZ4COzxLHflQ3E7baNVs4qAGoVL'
b'0vrCtpoAbwSSa/NSh+jnkVaLMoLDnXqrBUvScPSzSPAw0bC+hK9wTyJZtr60D74yDUfRrB'
b'K538I64ikMo6TlltzZFUlef2Fo9kCXvXJvlQmTBVodcEDQBwyww1R+px4RMbHoUQRj2/Yh'
b'zkx0vduo25xaYNRvlha96jgri497ThaRvtKOgvDYoD0yaL+dmB4x6xLNxH5CVE1pIss00S'
b'kidI8OGPe6Dr7qdR0ed7EEo6xiH7rlzceSKlbd3pxvmJmvoCJpOihIGjVfwxlwtriGxU/M'
b'FC/LKzT4cLwh1INFaqCgl1lBlAhzDYSgHCzOGkUHV0StvlCj1vZP5jFRqtT8pCnKwsGmTi'
b'l6dzmsz91ooYU8PZKhhukJeaPpaCRDTvW7i3o7ZmmB6MCzAfe9tc+hijHKKcY+nK6WdKYW'
b'Hq3oWHRkPdI6MF7lKZNblh/zJDb6KAwdHyilxt6zz48WZmx4o/tLl8ktcxEmkqc82Ef0f4'
b'YhyZBqwDTuwnBZBPKWvfqKbD9UGq96WHRAGBQNEA+JpYXCgGiAW8OhEUUPhsZlNBQaRA+E'
b'BpBhcGYoGQSXjvRDoHEsA6CJTg9/hh0/MbwS6HLkfsDbBuPwHvU7NnefeWcyQuaCyPhYGc'
b'iNjojL2XBnK/sZ7TQRs4c3K/epFekZ6oq+bhz1K1p4QeTcDT6pVrIwWDwec0d19O4eyi+6'
b'E5KudKvUdNQqIeWw6zcXI6uxtV6/OQW/9ixjzh7zkCdcdBKTZGQk2l+4GIt+T35WNmlIhX'
b'UhJNudC80m9lPXPAduzE6w+4yeWVOYPLM2TU6y1IQWbnRSPVlpHPbwwAswpp7a89zs0lF+'
b'08vcyw394mHL1w4x2M9nzkV4HslzfEjPTzQSXHnKhNsK9bB+6eGJUXtwd6BxVOqpgf6XmS'
b'P3JjTvFDWGzMKTJvCFp5zs3E70oYXzCddJKZ2bcIHRYLYDzWqjd1RpR3ZJ1rqiB++odo68'
b'+bHHvZymbF5RQ8zcw5Ueb7Q4HYN1GMolWtKpSHu1yhBarTIAn6TQPTqHbaLxkjPXCYjGj1'
b'XUE4uO1+0zC8c9e+mCGNkP5haNR4bSgqO+nU1IrwMiGnsqgs+RMyccFd1BhlI0ZziuG2Tp'
b'ODfaI0RVFmH2Wx38recOCwdz2UmHQ7YcxS4PW6rVNEwjpbsTZHH0pqymo+5kmcSvhxYUht'
b'q9tURLkbgLLyPh0B4ZrHlKC90IqsRGHQg2ZUsE8zZcXtfRvU6LhLbNUAr04dw5yYdneyQj'
b'c5Q1VeB7UHJqNyNH2/JaOpjyklbbvhXJ0fvcGbGr17nz5BytCa5IjzTzBUPvmaYoRcvkHC'
b'0frhQdnUmegHF+7bqdvuf8vOZBZxP0V6qXc34Y5ZRab6C2IzJoxgYM+ilIe1kn5s1nbZUP'
b'hiyDFfjG6Mu3DdBXnMPqV4mMeNDPW6IqGiBe30eVNOjYQp7F+3D1OGTDPLLw1Wl7eDEXjy'
b'bnsFiWWyK+q6VKgUZWCZRVnX+CLnCOVsYaQ8sCGmTQBw6mqAjdrccG5nSoLimfkxw941AS'
b'u3Hp6zzzjPHFAZMFOVcPP1QGDQfcTcC3bjjAAOI5V0E3ZO35cO9ZvSs8U+hI/KlhxbV7Vl'
b'vwRtRT4VxF3ZJ1fRtChaKJ7sUpFR01CjrcdS9bngvNeGZNSK9TmDh2PSft3WbQd7BNPOOP'
b'jksHgcGkK4XTkLeUY8MQRXdpKFEtKUpY2aFTqpZ8KO1sXx1lhp3DhXOKDBfOGTBcOGfIk6'
b'6GDZpi97UPM+pZY4Fo6kUwOuJQkPa9oiF0t+iA0C8aIPQ7+cTQI/uXBUEuNT1jpBndwViP'
b'eNFFjJVm+tX+KLSrKxlRH3QvkzWGHlXTuQGv2ox1O66+jA99Qfdnfzqb+zdyCzzyMGLGd+'
b'VA2ieCavtpTnqk9ntkxE/U7KxfzWZnwhlNaIUxnr42yXiX3uSNgUYzU+P0GM+WFoLJPGgS'
b'IKmtTB60SqOvhLs2UybEHQ9Z8vPFnCYRdkaMVmOTVZtYb+r8SOUgASYWGMKBktoi6ogJS9'
b'Ye2tF302eCnsx7cpzrhens4gY3TDENGyXDeXhuP4NXB6i5+MwiIQczDdyaj7vw/YzcBaAW'
b'r50DPUufeSjM0x0Uz9RzD4a5uoNudUhOVD1fd66jGbvDbh0SLy1LT+eda+nnnJMwpZ8L4C'
b'f1zotb7TNHUdoY4t2aJ7NB7RjSU7o06MPkLjg/Tyeprr9E1Y3u5kKdje7m0nQ0dhgGmtFV'
b'I514xqiNenzcRLNkPDmoHDJqoHQoz7yFR7Wcoj+xkLNdyR01RORmuNzvnJPSeeARERajXV'
b'azUDSDmFrQz+Yciozv9506PEShedIxDBulQ+LBxKAv0YtmlERd/eBOlFDm6FrxCsqtNmAp'
b'QUerJJBUvwfNNhFdVYX+IrqqStNR2TIgxIPs//NMc9qnrbUca4uIIXdGs0FaXLktPRac1R'
b'7a9xsHVQZ67M29Ms3SUGbZjxNVEnw8GB2o8WrutbDShd01hkAzRn+/8ATZwmlgj45m22GC'
b'fUSf0Jkb5GiePf0uV7YCl991ok8Uz266sqZMOR+I/i5bImq/70bHhC4CqrWMGwjZHWv3o0'
b'uTnGWRB6mn/ZA1803ZqXnSW+zOFeRNdhGC3Efo18SR5cd+/bRBsHziwRC7R16aPrXEkTtA'
b'zdwSPMRPa1jagPLZWr4013NO5D7DRCoCwlTKwWEyRSCaNBjAGHZSceNnmmlCc7J7RYRVdA'
b'eMN1gcfLXB4vB4g4XgNrrIDrmnVzPQcvUEe7Yi7W/BMIS+lccB4coOAvoE9czQ8RyQ88vr'
b'KU3DJn41u2jYEcQa7MQAXoW1lNZhPRKUWCLeOKtG5NHNYKgP0c1gmo46FlSPy/g2D47Sl/'
b'F1HosrMDoZjSx67XZflZ7ROEQGWu8kaGm5Q2SwNH4O57ewNZw7RDSGIp9OHSYaYOUBCZkB'
b'8WauPONH0D8MqbSjmnSQOQ3kLc3IhOr1IuN1dLNO4bDvIboPmZCjdajaAkGDMkCsP2UWCt'
b'qTAW7pTiYpWnMyLiO9ySC3tCYjtNaZjEspSMMO+tLMkV5bMo6lSI0c8m5OY7JQK0PGtVeF'
b'HNEfN0bRnCa8RhnxXeR2tXlyMes5GaK9KLM/UuqylxqkuxqtXCYXubwMIYaFFUeEy8saDc'
b'hKS5VEz4HmyWWzDt1HkYIOt41VlpSzIZDd2yFCRH3b2CKQ3jMmxIJJ9HnAJBlzhQXRVmmA'
b'nQDpUkUjdxItS4DqpjAIKTeUQUptJmnI8C4xSH3tD8LR14lBd7i4C8qaif30V860M0uraC'
b'muvqCsbSwdhbi0mFxQtgIdX1DGHNeQzhDk3ZUdMmTUtxSVye3lYXjVt1Ogz7+EO8yQqZKZ'
b'6Ogu148YrzyoluQq43J08xOkj1RGlAVX4PytQcVK0eYS7QlTIJD2m2u3uqvJFe4vJ6Jb9x'
b'TxnJ/s7cyy9QQlJxdaMRt8u2eRvsgLPCTQiqMtbzQonsg2158tCk/ox4ebMeh1SBO44fgL'
b'HzAPc4jcn4bK8DI2xPeYO0kBEaL8ZQKsdT0v37+Mn8qGwnc1/E2L5Gr0m4+xaPBD3UAPtz'
b'ZW8GrldBXgq1czG5S7f5KY/qP7rCoPSCeA6HVvh6yRboXfusVaOjRZ0le1LgN4y+45wr3F'
b'cwRqW2cwbgWSJtdhaEwHkSZf2cWXyVfZSyvwrbfSLB0MlEjrW4or0NwsWJIRtgdyRZbFCA'
b'hLkgYMS5KWNKe4oAE3QgWt2GDaz2pC5G0IL7uhZ/sahhkEqXo9qEHRS88YW78q3XI+JTlS'
b'LRtiV5rlguhYsVwC1JkzA23ejeDuiu8TzAg6qRYCcBKrngabLCOOPo8yizjhjaI4LAfWAK'
b'Pbb9vkq5/LIE16WWMFt2iC+uEkNHcL+TrkaV1/iJ3WR31XPObpDvNNRADdTgBGHS+qoJ6r'
b'VxDImJjefGe8HTN1UjxTG602yf9isEoPOoB58lU6XVQlP/hVSGxQ+ZHjeiyeoeLogW01TV'
b'5ZyFXy6rsVJPl1re4snYHUhzdWoPXhDU1H8i7IkGBqUOM+tG49qAMkeFZ2uAWF+2ou1uME'
b'ncF+fbs9hCE169ewU8g4R89ImtBfw0uUYTV9GjNib3WZvKpnhpbJa2i5pSXETB3d8Ksaz2'
b'uSaosN85BX1dKhO73q3axZChq+OSbwFuo0RSqixkoHIV+Rnk7dmwrJvKZUwyFNFvTFkAaQ'
b'Rwox0CrAzWWAL2cOh07VHeOFmEn7HZ4qB2i/1278Cstk9T2mDmFqHaHb2huT/GJRRYi7NJ'
b'zn4LjlZSqRclw7x8PrwV+kY5yEk3g8kn7lRrOXls2kfS+IRX7tRrNTz+b94ryja7SmVX6H'
b'L4tRLs2G/m46Zjccab4LxPjzb+PxRl2H9jTYCAZcFhVnLgmnMw0Yy4mTWG0/lr48/7fFu/'
b'r7TiStLhnQF7+X0GLsQjNRFHpBfDYBrVuNoaWZQOaoW0ce6SXXWQZa+9Z0pNQhQwbzMMmM'
b'H5HdC1noSf1GUIY4pL9GeEbfTLmF/KrPysFV6L1RB98OZqK0Sjj3xHDzpxqB82Xypza3zp'
b'JgT4lZ1p+6F4LTqBdqkj+jEx3QCf7kBUpNm0SWjui4xawRmfynkrXNEz4EBD30bb3ehA57'
b'2ib6tnRouG8yM18mcnF6Rlz1ZFkSXaNuvOmlLNJ68JiC1uOGpqOByDAkmhTUfs3h1e+6Ut'
b'yroSn3oI7iCozqwgJcrdqXcB7Ko7ZEGCaq5E3P9JG8qIAsLdPgInlTCuB0TtLcCB+GsGUW'
b'wFg3ZF6Od4pXxvWtkbCMGaORcB5zxzvNqFgRf7TlDIXk7Xp7GlPwt6vdaegmb7eNKzD+vn'
b'3HuALV9e2WccXMBGa3LIezXTcJGYc6oSoi029MU5nncZsmokZbQ16dDq8ZwHG9RRN4Q9sM'
b'JhbzCI8fxjI8fXHZlBl5vLmCgwYHKDYETAUbH7VnVXasGGcFOPdhijKDDF55YIm4bYpmaj'
b'/9agumUm+91oGRC1rwgvxgdIhY+sMb+mmMFWzD8eYYhYi6G6RtMA9mm48wT1NkmJYZMEzL'
b'DBlNsTKH6PsyVk0KMaID4ag0QxC5Zji62deKjnqWkgypDSiwqzuvoe29XV163V6BUT+C/s'
b'g8VmLPJ6AgBt1PGmFVh2ZieJNttIxJfgtv72KWJkvgLMmX4alDIe9ZAryXaR5D+oJRlCtt'
b'4uZIpR+skDN6sIIoftrBShkGLiQhOvGNIC4qg9EJRAfAS0VHGVyQIVVpAup03z/pPrZxWD'
b'+c+8c+ejQDQxp4u/4MPUTDVYBv+ZqRPS7GwoNa7CswKkbGrroVdowX3XuwJ9Xj5HJF2i8Y'
b'r5JvHFvnyTd9WA36xjdZRCbPO2/wrS8cIK2MOmuSI6NOBnVt1FkZNBh1Gldjo04G16szXJ'
b'mhR0e4JgC1jSdD+qN7xIRbHVhFCRs0visQvfW39fEPtSnPGN/M2adlaT9D1xABoXNwcOge'
b'AGhtCSn1S+VVi28ZqWeWcCM1an0KwBp+8tO+sV4tzJcYVjraj9ezPPkWLeAgtpuWk2hS37'
b'pbJ6NRAaITtgg/OmFL+mh2rybmK2z/WFrtX5UG8FtSltJ7Sh4Jm0oWiXeVbLB6s8gi0W6R'
b'hfSukEXUzo8F9HkXi/jtHUuZZvT7wLfOqAusAngYDg7PJpNFwK0MwFD3ndEakhGdR0ShbD'
b'vdnOYEzKK/vko+I6oLj+HcLr3KcG4U3zL5Fh0rQwWOjpWRPgzqPnBUQW0lwoYRDYwQNToR'
b'A/fRiRjQ0s/D79gsABOib2GDDQmK7OEReGQPP0/+7a59v0z+H+SUGTTsMAEA'
)).decode().splitlines()
def ConversionHeader(i: str, filename: OptStr ="unknown"):
t = i.lower()
import textwrap
html = textwrap.dedent("""
<!DOCTYPE html>
<html>
<head>
<style>
body{background-color:gray}
div{position:relative;background-color:white;margin:1em auto}
p{position:absolute;margin:0}
img{position:absolute}
</style>
</head>
<body>
""")
xml = textwrap.dedent("""
<?xml version="1.0"?>
<document name="%s">
"""
% filename
)
xhtml = textwrap.dedent("""
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
body{background-color:gray}
div{background-color:white;margin:1em;padding:1em}
p{white-space:pre-wrap}
</style>
</head>
<body>
""")
text = ""
json = '{"document": "%s", "pages": [\n' % filename
if t == "html":
r = html
elif t == "json":
r = json
elif t == "xml":
r = xml
elif t == "xhtml":
r = xhtml
else:
r = text
return r
def ConversionTrailer(i: str):
t = i.lower()
text = ""
json = "]\n}"
html = "</body>\n</html>\n"
xml = "</document>\n"
xhtml = html
if t == "html":
r = html
elif t == "json":
r = json
elif t == "xml":
r = xml
elif t == "xhtml":
r = xhtml
else:
r = text
return r
def adobe_glyph_names() -> tuple:
'''
Adobe Glyph List function
'''
if _adobe_unicodes == {}:
for line in _get_glyph_text():
if line.startswith("#"):
continue
gname, unc = line.split(";")
c = int("0x" + unc[:4], base=16)
_adobe_unicodes[gname] = c
return tuple(_adobe_unicodes.keys())
def adobe_glyph_unicodes() -> tuple:
'''
Adobe Glyph List function
'''
if _adobe_unicodes == {}:
for line in _get_glyph_text():
if line.startswith("#"):
continue
gname, unc = line.split(";")
c = int("0x" + unc[:4], base=16)
_adobe_unicodes[gname] = c
return tuple(_adobe_unicodes.values())
def annot_preprocess(page: "Page") -> int:
"""Prepare for annotation insertion on the page.
Returns:
Old page rotation value. Temporarily sets rotation to 0 when required.
"""
CheckParent(page)
if not page.parent.is_pdf:
raise ValueError("is no PDF")
old_rotation = page.rotation
if old_rotation != 0:
page.set_rotation(0)
return old_rotation
def annot_postprocess(page: "Page", annot: "Annot") -> None:
"""Clean up after annotation insertion.
Set ownership flag and store annotation in page annotation dictionary.
"""
#annot.parent = weakref.proxy(page)
assert isinstance( page, Page)
assert isinstance( annot, Annot)
annot.parent = page
page._annot_refs[id(annot)] = annot
annot.thisown = True
def canon(c):
assert isinstance(c, int)
# TODO: proper unicode case folding
# TODO: character equivalence (a matches ä, etc)
if c == 0xA0 or c == 0x2028 or c == 0x2029:
return ord(' ')
if c == ord('\r') or c == ord('\n') or c == ord('\t'):
return ord(' ')
if c >= ord('A') and c <= ord('Z'):
return c - ord('A') + ord('a')
return c
def chartocanon(s):
assert isinstance(s, str)
n, c = mupdf.fz_chartorune(s)
c = canon(c)
return n, c
def dest_is_valid(o, page_count, page_object_nums, names_list):
p = mupdf.pdf_dict_get( o, PDF_NAME('A'))
if (
mupdf.pdf_name_eq(
mupdf.pdf_dict_get( p, PDF_NAME('S')),
PDF_NAME('GoTo')
)
and not string_in_names_list(
mupdf.pdf_dict_get( p, PDF_NAME('D')),
names_list
)
):
return 0
p = mupdf.pdf_dict_get( o, PDF_NAME('Dest'))
if not p.m_internal:
pass
elif mupdf.pdf_is_string( p):
return string_in_names_list( p, names_list)
elif not dest_is_valid_page(
mupdf.pdf_array_get( p, 0),
page_object_nums,
page_count,
):
return 0
return 1
def dest_is_valid_page(obj, page_object_nums, pagecount):
num = mupdf.pdf_to_num(obj)
if num == 0:
return 0
for i in range(pagecount):
if page_object_nums[i] == num:
return 1
return 0
def find_string(s, needle):
assert isinstance(s, str)
for i in range(len(s)):
end = match_string(s[i:], needle)
if end is not None:
end += i
return i, end
return None, None
def get_pdf_now() -> str:
'''
"Now" timestamp in PDF Format
'''
import time
tz = "%s'%s'" % (
str(abs(time.altzone // 3600)).rjust(2, "0"),
str((abs(time.altzone // 60) % 60)).rjust(2, "0"),
)
tstamp = time.strftime("D:%Y%m%d%H%M%S", time.localtime())
if time.altzone > 0:
tstamp += "-" + tz
elif time.altzone < 0:
tstamp += "+" + tz
else:
pass
return tstamp
class ElementPosition(object):
"""Convert a dictionary with element position information to an object."""
def __init__(self):
pass
def make_story_elpos():
return ElementPosition()
def get_highlight_selection(page, start: point_like =None, stop: point_like =None, clip: rect_like =None) -> list:
"""Return rectangles of text lines between two points.
Notes:
The default of 'start' is top-left of 'clip'. The default of 'stop'
is bottom-reight of 'clip'.
Args:
start: start point_like
stop: end point_like, must be 'below' start
clip: consider this rect_like only, default is page rectangle
Returns:
List of line bbox intersections with the area established by the
parameters.
"""
# validate and normalize arguments
if clip is None:
clip = page.rect
clip = Rect(clip)
if start is None:
start = clip.tl
if stop is None:
stop = clip.br
clip.y0 = start.y
clip.y1 = stop.y
if clip.is_empty or clip.is_infinite:
return []
# extract text of page, clip only, no images, expand ligatures
blocks = page.get_text(
"dict", flags=0, clip=clip,
)["blocks"]
lines = [] # will return this list of rectangles
for b in blocks:
bbox = Rect(b["bbox"])
if bbox.is_infinite or bbox.is_empty:
continue
for line in b["lines"]:
bbox = Rect(line["bbox"])
if bbox.is_infinite or bbox.is_empty:
continue
lines.append(bbox)
if lines == []: # did not select anything
return lines
lines.sort(key=lambda bbox: bbox.y1) # sort by vertical positions
# cut off prefix from first line if start point is close to its top
bboxf = lines.pop(0)
if bboxf.y0 - start.y <= 0.1 * bboxf.height: # close enough?
r = Rect(start.x, bboxf.y0, bboxf.br) # intersection rectangle
if not (r.is_empty or r.is_infinite):
lines.insert(0, r) # insert again if not empty
else:
lines.insert(0, bboxf) # insert again
if lines == []: # the list might have been emptied
return lines
# cut off suffix from last line if stop point is close to its bottom
bboxl = lines.pop()
if stop.y - bboxl.y1 <= 0.1 * bboxl.height: # close enough?
r = Rect(bboxl.tl, stop.x, bboxl.y1) # intersection rectangle
if not (r.is_empty or r.is_infinite):
lines.append(r) # append if not empty
else:
lines.append(bboxl) # append again
return lines
def glyph_name_to_unicode(name: str) -> int:
'''
Adobe Glyph List function
'''
if _adobe_unicodes == {}:
for line in _get_glyph_text():
if line.startswith("#"):
continue
gname, unc = line.split(";")
c = int(unc[:4], base=16)
_adobe_unicodes[gname] = c
return _adobe_unicodes.get(name, 65533)
def hdist(dir, a, b):
dx = b.x - a.x
dy = b.y - a.y
return mupdf.fz_abs(dx * dir.x + dy * dir.y)
def make_table(rect: rect_like =(0, 0, 1, 1), cols: int =1, rows: int =1) -> list:
"""Return a list of (rows x cols) equal sized rectangles.
Notes:
A utility to fill a given area with table cells of equal size.
Args:
rect: rect_like to use as the table area
rows: number of rows
cols: number of columns
Returns:
A list with <rows> items, where each item is a list of <cols>
PyMuPDF Rect objects of equal sizes.
"""
rect = Rect(rect) # ensure this is a Rect
if rect.is_empty or rect.is_infinite:
raise ValueError("rect must be finite and not empty")
tl = rect.tl
height = rect.height / rows # height of one table cell
width = rect.width / cols # width of one table cell
delta_h = (width, 0, width, 0) # diff to next right rect
delta_v = (0, height, 0, height) # diff to next lower rect
r = Rect(tl, tl.x + width, tl.y + height) # first rectangle
# make the first row
row = [r]
for i in range(1, cols):
r += delta_h # build next rect to the right
row.append(r)
# make result, starts with first row
rects = [row]
for i in range(1, rows):
row = rects[i - 1] # take previously appended row
nrow = [] # the new row to append
for r in row: # for each previous cell add its downward copy
nrow.append(r + delta_v)
rects.append(nrow) # append new row to result
return rects
def util_ensure_widget_calc(annot):
'''
Ensure that widgets with /AA/C JavaScript are in array AcroForm/CO
'''
annot_obj = mupdf.pdf_annot_obj(annot.this)
pdf = mupdf.pdf_get_bound_document(annot_obj)
PDFNAME_CO = mupdf.pdf_new_name("CO") # = PDF_NAME(CO)
acro = mupdf.pdf_dict_getl( # get AcroForm dict
mupdf.pdf_trailer(pdf),
PDF_NAME('Root'),
PDF_NAME('AcroForm'),
)
CO = mupdf.pdf_dict_get(acro, PDFNAME_CO) # = AcroForm/CO
if not mupdf.pdf_is_array(CO):
CO = mupdf.pdf_dict_put_array(acro, PDFNAME_CO, 2)
n = mupdf.pdf_array_len(CO)
found = 0
xref = mupdf.pdf_to_num(annot_obj)
for i in range(n):
nxref = mupdf.pdf_to_num(mupdf.pdf_array_get(CO, i))
if xref == nxref:
found = 1
break
if not found:
mupdf.pdf_array_push(CO, mupdf.pdf_new_indirect(pdf, xref, 0))
def util_make_rect( *args, p0=None, p1=None, x0=None, y0=None, x1=None, y1=None):
'''
Helper for initialising rectangle classes.
2022-09-02: This is quite different from PyMuPDF's util_make_rect(), which
uses `goto` in ways that don't easily translate to Python.
Returns (x0, y0, x1, y1) derived from <args>, then override with p0, p1,
x0, y0, x1, y1 if they are not None.
Accepts following forms for <args>:
() returns all zeros.
(top-left, bottom-right)
(top-left, x1, y1)
(x0, y0, bottom-right)
(x0, y0, x1, y1)
(rect)
Where top-left and bottom-right are (x, y) or something with .x, .y
members; rect is something with .x0, .y0, .x1, and .y1 members.
2023-11-18: we now override with p0, p1, x0, y0, x1, y1 if not None.
'''
def get_xy( arg):
if isinstance( arg, (list, tuple)) and len( arg) == 2:
return arg[0], arg[1]
if isinstance( arg, (Point, mupdf.FzPoint, mupdf.fz_point)):
return arg.x, arg.y
return None, None
def make_tuple( a):
if isinstance( a, tuple):
return a
if isinstance( a, Point):
return a.x, a.y
elif isinstance( a, (Rect, IRect, mupdf.FzRect, mupdf.fz_rect)):
return a.x0, a.y0, a.x1, a.y1
if not isinstance( a, (list, tuple)):
a = a,
return a
def handle_args():
if len(args) == 0:
return 0, 0, 0, 0
elif len(args) == 1:
arg = args[0]
if isinstance( arg, (list, tuple)) and len( arg) == 2:
p1, p2 = arg
return *p1, *p2
if isinstance( arg, (list, tuple)) and len( arg) == 3:
a, b, c = arg
a = make_tuple(a)
b = make_tuple(b)
c = make_tuple(c)
ret = *a, *b, *c
return ret
arg = make_tuple( arg)
return arg
elif len(args) == 2:
return get_xy( args[0]) + get_xy( args[1])
elif len(args) == 3:
x0, y0 = get_xy( args[0])
if (x0, y0) != (None, None):
return x0, y0, args[1], args[2]
x1, y1 = get_xy( args[2])
if (x1, y1) != (None, None):
return args[0], args[1], x1, y1
elif len(args) == 4:
return args[0], args[1], args[2], args[3]
raise Exception( f'Unrecognised args: {args}')
ret_x0, ret_y0, ret_x1, ret_y1 = handle_args()
if p0 is not None: ret_x0, ret_y0 = get_xy(p0)
if p1 is not None: ret_x1, ret_y1 = get_xy(p1)
if x0 is not None: ret_x0 = x0
if y0 is not None: ret_y0 = y0
if x1 is not None: ret_x1 = x1
if y1 is not None: ret_y1 = y1
return ret_x0, ret_y0, ret_x1, ret_y1
def util_make_irect( *args, p0=None, p1=None, x0=None, y0=None, x1=None, y1=None):
a, b, c, d = util_make_rect( *args, p0=p0, p1=p1, x0=x0, y0=y0, x1=x1, y1=y1)
def convert(x):
ret = int(x)
return ret
a = convert(a)
b = convert(b)
c = convert(c)
d = convert(d)
return a, b, c, d
def util_round_rect( rect):
return JM_py_from_irect(mupdf.fz_round_rect(JM_rect_from_py(rect)))
def util_transform_rect( rect, matrix):
if g_use_extra:
return extra.util_transform_rect( rect, matrix)
return JM_py_from_rect(mupdf.fz_transform_rect(JM_rect_from_py(rect), JM_matrix_from_py(matrix)))
def util_intersect_rect( r1, r2):
return JM_py_from_rect(
mupdf.fz_intersect_rect(
JM_rect_from_py(r1),
JM_rect_from_py(r2),
)
)
def util_is_point_in_rect( p, r):
return mupdf.fz_is_point_inside_rect(
JM_point_from_py(p),
JM_rect_from_py(r),
)
def util_include_point_in_rect( r, p):
return JM_py_from_rect(
mupdf.fz_include_point_in_rect(
JM_rect_from_py(r),
JM_point_from_py(p),
)
)
def util_point_in_quad( P, Q):
p = JM_point_from_py(P)
q = JM_quad_from_py(Q)
return mupdf.fz_is_point_inside_quad(p, q)
def util_transform_point( point, matrix):
return JM_py_from_point(
mupdf.fz_transform_point(
JM_point_from_py(point),
JM_matrix_from_py(matrix),
)
)
def util_union_rect( r1, r2):
return JM_py_from_rect(
mupdf.fz_union_rect(
JM_rect_from_py(r1),
JM_rect_from_py(r2),
)
)
def util_concat_matrix( m1, m2):
return JM_py_from_matrix(
mupdf.fz_concat(
JM_matrix_from_py(m1),
JM_matrix_from_py(m2),
)
)
def util_invert_matrix(matrix):
if 0:
# Use MuPDF's fz_invert_matrix().
if isinstance( matrix, (tuple, list)):
matrix = mupdf.FzMatrix( *matrix)
elif isinstance( matrix, mupdf.fz_matrix):
matrix = mupdf.FzMatrix( matrix)
elif isinstance( matrix, Matrix):
matrix = mupdf.FzMatrix( matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f)
assert isinstance( matrix, mupdf.FzMatrix), f'{type(matrix)=}: {matrix}'
ret = mupdf.fz_invert_matrix( matrix)
if ret == matrix and (0
or abs( matrix.a - 1) >= sys.float_info.epsilon
or abs( matrix.b - 0) >= sys.float_info.epsilon
or abs( matrix.c - 0) >= sys.float_info.epsilon
or abs( matrix.d - 1) >= sys.float_info.epsilon
):
# Inversion not possible.
return 1, ()
return 0, (ret.a, ret.b, ret.c, ret.d, ret.e, ret.f)
# Do inversion in python.
src = JM_matrix_from_py(matrix)
a = src.a
det = a * src.d - src.b * src.c
if det < -sys.float_info.epsilon or det > sys.float_info.epsilon:
dst = mupdf.FzMatrix()
rdet = 1 / det
dst.a = src.d * rdet
dst.b = -src.b * rdet
dst.c = -src.c * rdet
dst.d = a * rdet
a = -src.e * dst.a - src.f * dst.c
dst.f = -src.e * dst.b - src.f * dst.d
dst.e = a
return 0, (dst.a, dst.b, dst.c, dst.d, dst.e, dst.f)
return 1, ()
def util_measure_string( text, fontname, fontsize, encoding):
font = mupdf.fz_new_base14_font(fontname)
w = 0
pos = 0
while pos < len(text):
t, c = mupdf.fz_chartorune(text[pos:])
pos += t
if encoding == mupdf.PDF_SIMPLE_ENCODING_GREEK:
c = mupdf.fz_iso8859_7_from_unicode(c)
elif encoding == mupdf.PDF_SIMPLE_ENCODING_CYRILLIC:
c = mupdf.fz_windows_1251_from_unicode(c)
else:
c = mupdf.fz_windows_1252_from_unicode(c)
if c < 0:
c = 0xB7
g = mupdf.fz_encode_character(font, c)
dw = mupdf.fz_advance_glyph(font, g, 0)
w += dw
ret = w * fontsize
return ret
def util_sine_between(C, P, Q):
# for points C, P, Q compute the sine between lines CP and QP
c = JM_point_from_py(C)
p = JM_point_from_py(P)
q = JM_point_from_py(Q)
s = mupdf.fz_normalize_vector(mupdf.fz_make_point(q.x - p.x, q.y - p.y))
m1 = mupdf.fz_make_matrix(1, 0, 0, 1, -p.x, -p.y)
m2 = mupdf.fz_make_matrix(s.x, -s.y, s.y, s.x, 0, 0)
m1 = mupdf.fz_concat(m1, m2)
c = mupdf.fz_transform_point(c, m1)
c = mupdf.fz_normalize_vector(c)
return c.y
def util_hor_matrix(C, P):
'''
Return the matrix that maps two points C, P to the x-axis such that
C -> (0,0) and the image of P have the same distance.
'''
c = JM_point_from_py(C)
p = JM_point_from_py(P)
# compute (cosine, sine) of vector P-C with double precision:
s = mupdf.fz_normalize_vector(mupdf.fz_make_point(p.x - c.x, p.y - c.y))
m1 = mupdf.fz_make_matrix(1, 0, 0, 1, -c.x, -c.y)
m2 = mupdf.fz_make_matrix(s.x, -s.y, s.y, s.x, 0, 0)
return JM_py_from_matrix(mupdf.fz_concat(m1, m2))
def match_string(h0, n0):
h = 0
n = 0
e = h
delta_h, hc = chartocanon(h0[h:])
h += delta_h
delta_n, nc = chartocanon(n0[n:])
n += delta_n
while hc == nc:
e = h
if hc == ord(' '):
while 1:
delta_h, hc = chartocanon(h0[h:])
h += delta_h
if hc != ord(' '):
break
else:
delta_h, hc = chartocanon(h0[h:])
h += delta_h
if nc == ord(' '):
while 1:
delta_n, nc = chartocanon(n0[n:])
n += delta_n
if nc != ord(' '):
break
else:
delta_n, nc = chartocanon(n0[n:])
n += delta_n
return None if nc != 0 else e
def on_highlight_char(hits, line, ch):
assert hits
assert isinstance(line, mupdf.FzStextLine)
assert isinstance(ch, mupdf.FzStextChar)
vfuzz = ch.m_internal.size * hits.vfuzz
hfuzz = ch.m_internal.size * hits.hfuzz
ch_quad = JM_char_quad(line, ch)
if hits.len > 0:
# fixme: end = hits.quads[-1]
quad = hits.quads[hits.len - 1]
end = JM_quad_from_py(quad)
if ( 1
and hdist(line.m_internal.dir, end.lr, ch_quad.ll) < hfuzz
and vdist(line.m_internal.dir, end.lr, ch_quad.ll) < vfuzz
and hdist(line.m_internal.dir, end.ur, ch_quad.ul) < hfuzz
and vdist(line.m_internal.dir, end.ur, ch_quad.ul) < vfuzz
):
end.ur = ch_quad.ur
end.lr = ch_quad.lr
assert hits.quads[-1] == end
return
hits.quads.append(ch_quad)
hits.len += 1
def page_merge(doc_des, doc_src, page_from, page_to, rotate, links, copy_annots, graft_map):
'''
Deep-copies a source page to the target.
Modified version of function of pdfmerge.c: we also copy annotations, but
we skip some subtypes. In addition we rotate output.
'''
if g_use_extra:
#log( 'Calling C++ extra.page_merge()')
return extra.page_merge( doc_des, doc_src, page_from, page_to, rotate, links, copy_annots, graft_map)
# list of object types (per page) we want to copy
known_page_objs = [
PDF_NAME('Contents'),
PDF_NAME('Resources'),
PDF_NAME('MediaBox'),
PDF_NAME('CropBox'),
PDF_NAME('BleedBox'),
PDF_NAME('TrimBox'),
PDF_NAME('ArtBox'),
PDF_NAME('Rotate'),
PDF_NAME('UserUnit'),
]
page_ref = mupdf.pdf_lookup_page_obj(doc_src, page_from)
# make new page dict in dest doc
page_dict = mupdf.pdf_new_dict(doc_des, 4)
mupdf.pdf_dict_put(page_dict, PDF_NAME('Type'), PDF_NAME('Page'))
# copy objects of source page into it
for i in range( len(known_page_objs)):
obj = mupdf.pdf_dict_get_inheritable( page_ref, known_page_objs[i])
if obj.m_internal:
#log( '{=type(graft_map) type(graft_map.this)}')
mupdf.pdf_dict_put( page_dict, known_page_objs[i], mupdf.pdf_graft_mapped_object(graft_map.this, obj))
# Copy annotations, but skip Link, Popup, IRT, Widget types
# If selected, remove dict keys P (parent) and Popup
if copy_annots:
old_annots = mupdf.pdf_dict_get( page_ref, PDF_NAME('Annots'))
n = mupdf.pdf_array_len( old_annots)
if n > 0:
new_annots = mupdf.pdf_dict_put_array( page_dict, PDF_NAME('Annots'), n)
for i in range(n):
o = mupdf.pdf_array_get( old_annots, i)
if not o.m_internal or not mupdf.pdf_is_dict(o):
continue # skip non-dict items
if mupdf.pdf_dict_gets( o, "IRT").m_internal:
continue
subtype = mupdf.pdf_dict_get( o, PDF_NAME('Subtype'))
if mupdf.pdf_name_eq( subtype, PDF_NAME('Link')):
continue
if mupdf.pdf_name_eq( subtype, PDF_NAME('Popup')):
continue
if mupdf.pdf_name_eq( subtype, PDF_NAME('Widget')):
mupdf.fz_warn( "skipping widget annotation")
continue
if mupdf.pdf_name_eq(subtype, PDF_NAME('Widget')):
continue
mupdf.pdf_dict_del( o, PDF_NAME('Popup'))
mupdf.pdf_dict_del( o, PDF_NAME('P'))
copy_o = mupdf.pdf_graft_mapped_object( graft_map.this, o)
annot = mupdf.pdf_new_indirect( doc_des, mupdf.pdf_to_num( copy_o), 0)
mupdf.pdf_array_push( new_annots, annot)
# rotate the page
if rotate != -1:
mupdf.pdf_dict_put_int( page_dict, PDF_NAME('Rotate'), rotate)
# Now add the page dictionary to dest PDF
ref = mupdf.pdf_add_object( doc_des, page_dict)
# Insert new page at specified location
mupdf.pdf_insert_page( doc_des, page_to, ref)
def paper_rect(s: str) -> Rect:
"""Return a Rect for the paper size indicated in string 's'. Must conform to the argument of method 'PaperSize', which will be invoked.
"""
width, height = paper_size(s)
return Rect(0.0, 0.0, width, height)
def paper_size(s: str) -> tuple:
"""Return a tuple (width, height) for a given paper format string.
Notes:
'A4-L' will return (842, 595), the values for A4 landscape.
Suffix '-P' and no suffix return the portrait tuple.
"""
size = s.lower()
f = "p"
if size.endswith("-l"):
f = "l"
size = size[:-2]
if size.endswith("-p"):
size = size[:-2]
rc = paper_sizes().get(size, (-1, -1))
if f == "p":
return rc
return (rc[1], rc[0])
def paper_sizes():
"""Known paper formats @ 72 dpi as a dictionary. Key is the format string
like "a4" for ISO-A4. Value is the tuple (width, height).
Information taken from the following web sites:
www.din-formate.de
www.din-formate.info/amerikanische-formate.html
www.directtools.de/wissen/normen/iso.htm
"""
return {
"a0": (2384, 3370),
"a1": (1684, 2384),
"a10": (74, 105),
"a2": (1191, 1684),
"a3": (842, 1191),
"a4": (595, 842),
"a5": (420, 595),
"a6": (298, 420),
"a7": (210, 298),
"a8": (147, 210),
"a9": (105, 147),
"b0": (2835, 4008),
"b1": (2004, 2835),
"b10": (88, 125),
"b2": (1417, 2004),
"b3": (1001, 1417),
"b4": (709, 1001),
"b5": (499, 709),
"b6": (354, 499),
"b7": (249, 354),
"b8": (176, 249),
"b9": (125, 176),
"c0": (2599, 3677),
"c1": (1837, 2599),
"c10": (79, 113),
"c2": (1298, 1837),
"c3": (918, 1298),
"c4": (649, 918),
"c5": (459, 649),
"c6": (323, 459),
"c7": (230, 323),
"c8": (162, 230),
"c9": (113, 162),
"card-4x6": (288, 432),
"card-5x7": (360, 504),
"commercial": (297, 684),
"executive": (522, 756),
"invoice": (396, 612),
"ledger": (792, 1224),
"legal": (612, 1008),
"legal-13": (612, 936),
"letter": (612, 792),
"monarch": (279, 540),
"tabloid-extra": (864, 1296),
}
if mupdf_version_tuple >= (1, 23, 8):
def pdf_lookup_page_loc(doc, needle):
return mupdf.pdf_lookup_page_loc(doc, needle)
else:
def pdf_lookup_page_loc_imp(doc, node, skip, parentp, indexp):
assert isinstance(node, mupdf.PdfObj)
assert isinstance(skip, list) and len(skip) == 1
assert isinstance(indexp, list) and len(indexp) == 1
assert isinstance(parentp, list) and len(parentp) == 1 and isinstance(parentp[0], mupdf.PdfObj)
# Copy of MuPDF's internal pdf_lookup_page_loc_imp().
hit = None
stack = []
try:
while 1:
kids = mupdf.pdf_dict_get(node, PDF_NAME('Kids'))
len_ = mupdf.pdf_array_len( kids)
if len_ == 0:
raise Exception("malformed page tree")
# Every node we need to unmark goes into the stack
stack.append(node)
if mupdf.pdf_mark_obj( node):
raise Exception( "cycle in page tree")
for i in range(len_):
kid = mupdf.pdf_array_get( kids, i)
type_ = mupdf.pdf_dict_get( kid, PDF_NAME('Type'))
if type_.m_internal:
a = mupdf.pdf_name_eq( type_, PDF_NAME('Pages'))
else:
a = (
mupdf.pdf_dict_get( kid, PDF_NAME('Kids')).m_internal
and not mupdf.pdf_dict_get( kid, PDF_NAME('MediaBox')).m_internal
)
if a:
count = mupdf.pdf_dict_get_int( kid, PDF_NAME('Count'))
if (skip[0] < count):
node = kid
break
else:
skip[0] -= count
else:
if type_.m_internal:
a = not mupdf.pdf_name_eq( type_, PDF_NAME('Page'))
else:
a = not mupdf.pdf_dict_get( kid, PDF_NAME('MediaBox')).m_internal
if a:
mupdf.fz_warn( f"non-page object in page tree ({mupdf.pdf_to_name( type_)})")
if skip[0] == 0:
parentp[0] = node
indexp[0] = i
hit = kid
break
else:
skip[0] -= 1
# If i < len && hit != NULL the desired page was found in the
# Kids array, done. If i < len && hit == NULL the found page tree
# node contains a Kids array that contains the desired page, loop
# back to top to extract it. When i == len the Kids array has been
# exhausted without finding the desired page, give up.
if not ((hit is None or hit.m_internal is None) and i < len_):
break
finally:
for i in range(len(stack), 0, -1): # (i = stack_len; i > 0; i--)
mupdf.pdf_unmark_obj( stack[i-1])
return hit
def pdf_lookup_page_loc(doc, needle):
'''
Copy of MuPDF's internal pdf_lookup_page_loc().
'''
root = mupdf.pdf_dict_get( mupdf.pdf_trailer( doc), PDF_NAME('Root'))
node = mupdf.pdf_dict_get( root, PDF_NAME('Pages'))
skip = [needle]
if not node.m_internal:
raise Exception("cannot find page tree")
parentp = [mupdf.PdfObj()]
indexp = [0]
hit = pdf_lookup_page_loc_imp(doc, node, skip, parentp, indexp)
skip = skip[0]
parentp = parentp[0]
indexp = indexp[0]
if not hit.m_internal:
raise Exception("cannot find page %d in page tree" % needle+1)
return hit, parentp, indexp # We don't seem to return skip.
def pdfobj_string(o, prefix=''):
'''
Returns description of mupdf.PdfObj (wrapper for pdf_obj) <o>.
'''
assert 0, 'use mupdf.pdf_debug_obj() ?'
ret = ''
if mupdf.pdf_is_array(o):
l = mupdf.pdf_array_len(o)
ret += f'array {l}\n'
for i in range(l):
oo = mupdf.pdf_array_get(o, i)
ret += pdfobj_string(oo, prefix + ' ')
ret += '\n'
elif mupdf.pdf_is_bool(o):
ret += f'bool: {o.array_get_bool()}\n'
elif mupdf.pdf_is_dict(o):
l = mupdf.pdf_dict_len(o)
ret += f'dict {l}\n'
for i in range(l):
key = mupdf.pdf_dict_get_key(o, i)
value = mupdf.pdf_dict_get( o, key)
ret += f'{prefix} {key}: '
ret += pdfobj_string( value, prefix + ' ')
ret += '\n'
elif mupdf.pdf_is_embedded_file(o):
ret += f'embedded_file: {o.embedded_file_name()}\n'
elif mupdf.pdf_is_indirect(o):
ret += f'indirect: ...\n'
elif mupdf.pdf_is_int(o):
ret += f'int: {mupdf.pdf_to_int(o)}\n'
elif mupdf.pdf_is_jpx_image(o):
ret += f'jpx_image:\n'
elif mupdf.pdf_is_name(o):
ret += f'name: {mupdf.pdf_to_name(o)}\n'
elif o.pdf_is_null:
ret += f'null\n'
#elif o.pdf_is_number:
# ret += f'number\n'
elif o.pdf_is_real:
ret += f'real: {o.pdf_to_real()}\n'
elif mupdf.pdf_is_stream(o):
ret += f'stream\n'
elif mupdf.pdf_is_string(o):
ret += f'string: {mupdf.pdf_to_string(o)}\n'
else:
ret += '<>\n'
return ret
def repair_mono_font(page: "Page", font: "Font") -> None:
"""Repair character spacing for mono fonts.
Notes:
Some mono-spaced fonts are displayed with a too large character
distance, e.g. "a b c" instead of "abc". This utility adds an entry
"/W[0 65535 w]" to the descendent font(s) of font. The float w is
taken to be the width of 0x20 (space).
This should enforce viewers to use 'w' as the character width.
Args:
page: pymupdf.Page object.
font: pymupdf.Font object.
"""
if not font.flags["mono"]: # font not flagged as monospaced
return None
doc = page.parent # the document
fontlist = page.get_fonts() # list of fonts on page
xrefs = [ # list of objects referring to font
f[0]
for f in fontlist
if (f[3] == font.name and f[4].startswith("F") and f[5].startswith("Identity"))
]
if xrefs == []: # our font does not occur
return
xrefs = set(xrefs) # drop any double counts
width = int(round((font.glyph_advance(32) * 1000)))
for xref in xrefs:
if not TOOLS.set_font_width(doc, xref, width):
log("Cannot set width for '%s' in xref %i" % (font.name, xref))
def sRGB_to_pdf(srgb: int) -> tuple:
"""Convert sRGB color code to a PDF color triple.
There is **no error checking** for performance reasons!
Args:
srgb: (int) RRGGBB (red, green, blue), each color in range(255).
Returns:
Tuple (red, green, blue) each item in interval 0 <= item <= 1.
"""
t = sRGB_to_rgb(srgb)
return t[0] / 255.0, t[1] / 255.0, t[2] / 255.0
def sRGB_to_rgb(srgb: int) -> tuple:
"""Convert sRGB color code to an RGB color triple.
There is **no error checking** for performance reasons!
Args:
srgb: (int) RRGGBB (red, green, blue), each color in range(255).
Returns:
Tuple (red, green, blue) each item in interval 0 <= item <= 255.
"""
r = srgb >> 16
g = (srgb - (r << 16)) >> 8
b = srgb - (r << 16) - (g << 8)
return (r, g, b)
def string_in_names_list(p, names_list):
n = mupdf.pdf_array_len( names_list) if names_list else 0
str_ = mupdf.pdf_to_text_string( p)
for i in range(0, n, 2):
if mupdf.pdf_to_text_string( mupdf.pdf_array_get( names_list, i)) == str_:
return 1
return 0
def strip_outline(doc, outlines, page_count, page_object_nums, names_list):
'''
Returns (count, first, prev).
'''
first = None
count = 0
current = outlines
prev = None
while current.m_internal:
# Strip any children to start with. This takes care of
# First / Last / Count for us.
nc = strip_outlines(doc, current, page_count, page_object_nums, names_list)
if not dest_is_valid(current, page_count, page_object_nums, names_list):
if nc == 0:
# Outline with invalid dest and no children. Drop it by
# pulling the next one in here.
next = mupdf.pdf_dict_get(current, PDF_NAME('Next'))
if not next.m_internal:
# There is no next one to pull in
if prev.m_internal:
mupdf.pdf_dict_del(prev, PDF_NAME('Next'))
elif prev.m_internal:
mupdf.pdf_dict_put(prev, PDF_NAME('Next'), next)
mupdf.pdf_dict_put(next, PDF_NAME('Prev'), prev)
else:
mupdf.pdf_dict_del(next, PDF_NAME('Prev'))
current = next
else:
# Outline with invalid dest, but children. Just drop the dest.
mupdf.pdf_dict_del(current, PDF_NAME('Dest'))
mupdf.pdf_dict_del(current, PDF_NAME('A'))
current = mupdf.pdf_dict_get(current, PDF_NAME('Next'))
else:
# Keep this one
if not first or not first.m_internal:
first = current
prev = current
current = mupdf.pdf_dict_get(current, PDF_NAME('Next'))
count += 1
return count, first, prev
def strip_outlines(doc, outlines, page_count, page_object_nums, names_list):
if not outlines.m_internal:
return 0
first = mupdf.pdf_dict_get(outlines, PDF_NAME('First'))
if not first.m_internal:
nc = 0
else:
nc, first, last = strip_outline(doc, first, page_count, page_object_nums, names_list)
if nc == 0:
mupdf.pdf_dict_del(outlines, PDF_NAME('First'))
mupdf.pdf_dict_del(outlines, PDF_NAME('Last'))
mupdf.pdf_dict_del(outlines, PDF_NAME('Count'))
else:
old_count = mupdf.pdf_to_int(mupdf.pdf_dict_get(outlines, PDF_NAME('Count')))
mupdf.pdf_dict_put(outlines, PDF_NAME('First'), first)
mupdf.pdf_dict_put(outlines, PDF_NAME('Last'), last)
mupdf.pdf_dict_put(outlines, PDF_NAME('Count'), mupdf.pdf_new_int(nc if old_count > 0 else -nc))
return nc
trace_device_FILL_PATH = 1
trace_device_STROKE_PATH = 2
trace_device_CLIP_PATH = 3
trace_device_CLIP_STROKE_PATH = 4
def unicode_to_glyph_name(ch: int) -> str:
'''
Adobe Glyph List function
'''
if _adobe_glyphs == {}:
for line in _get_glyph_text():
if line.startswith("#"):
continue
name, unc = line.split(";")
uncl = unc.split()
for unc in uncl:
c = int(unc[:4], base=16)
_adobe_glyphs[c] = name
return _adobe_glyphs.get(ch, ".notdef")
def vdist(dir, a, b):
dx = b.x - a.x
dy = b.y - a.y
return mupdf.fz_abs(dx * dir.y + dy * dir.x)
def apply_pages(
path,
pagefn,
*,
pagefn_args=(),
pagefn_kwargs=dict(),
initfn=None,
initfn_args=(),
initfn_kwargs=dict(),
pages=None,
method='single',
concurrency=None,
_stats=False,
):
'''
Returns list of results from `pagefn()`, optionally using concurrency for
speed.
Args:
path:
Path of document.
pagefn:
Function to call for each page; is passed (page, *pagefn_args,
**pagefn_kwargs). Return value is added to list that we return. If
`method` is not 'single', must be a top-level function - nested
functions don't work with concurrency.
pagefn_args
pagefn_kwargs:
Additional args to pass to `pagefn`. Must be picklable.
initfn:
If true, called once in each worker process; is passed
(*initfn_args, **initfn_kwargs).
initfn_args
initfn_kwargs:
Args to pass to initfn. Must be picklable.
pages:
List of page numbers to process, or None to include all pages.
method:
'single'
Do not use concurrency.
'mp'
Operate concurrently using Python's `multiprocessing` module.
'fork'
Operate concurrently using custom implementation with
`os.fork()`. Does not work on Windows.
concurrency:
Number of worker processes to use when operating concurrently. If
None, we use the number of available CPUs.
_stats:
Internal, may change or be removed. If true, we output simple
timing diagnostics.
Note: We require a file path rather than a Document, because Document
instances do not work properly after a fork - internal file descriptor
offsets are shared between the parent and child processes.
'''
if _stats:
t0 = time.time()
if method == 'single':
if initfn:
initfn(*initfn_args, **initfn_kwargs)
ret = list()
document = Document(path)
for page in document:
r = pagefn(page, *pagefn_args, **initfn_kwargs)
ret.append(r)
else:
# Use concurrency.
#
from . import _apply_pages
if pages is None:
if _stats:
t = time.time()
with Document(path) as document:
num_pages = len(document)
pages = list(range(num_pages))
if _stats:
t = time.time() - t
log(f'{t:.2f}s: count pages.')
if _stats:
t = time.time()
if method == 'mp':
ret = _apply_pages._multiprocessing(
path,
pages,
pagefn,
pagefn_args,
pagefn_kwargs,
initfn,
initfn_args,
initfn_kwargs,
concurrency,
_stats,
)
elif method == 'fork':
ret = _apply_pages._fork(
path,
pages,
pagefn,
pagefn_args,
pagefn_kwargs,
initfn,
initfn_args,
initfn_kwargs,
concurrency,
_stats,
)
else:
assert 0, f'Unrecognised {method=}.'
if _stats:
t = time.time() - t
log(f'{t:.2f}s: work.')
if _stats:
t = time.time() - t0
log(f'{t:.2f}s: total.')
return ret
def get_text(
path,
*,
pages=None,
method='single',
concurrency=None,
option='text',
clip=None,
flags=None,
textpage=None,
sort=False,
delimiters=None,
_stats=False,
):
'''
Returns list of results from `Page.get_text()`, optionally using
concurrency for speed.
Args:
path:
Path of document.
pages:
List of page numbers to process, or None to include all pages.
method:
'single'
Do not use concurrency.
'mp'
Operate concurrently using Python's `multiprocessing` module.
'fork'
Operate concurrently using custom implementation with
`os.fork`. Does not work on Windows.
concurrency:
Number of worker processes to use when operating concurrently. If
None, we use the number of available CPUs.
option
clip
flags
textpage
sort
delimiters:
Passed to internal calls to `Page.get_text()`.
'''
args_dict = dict(
option=option,
clip=clip,
flags=flags,
textpage=textpage,
sort=sort,
delimiters=delimiters,
)
return apply_pages(
path,
Page.get_text,
pagefn_kwargs=args_dict,
pages=pages,
method=method,
concurrency=concurrency,
_stats=_stats,
)
class TOOLS:
'''
We use @staticmethod to avoid the need to create an instance of this class.
'''
def _derotate_matrix(page):
if isinstance(page, mupdf.PdfPage):
return JM_py_from_matrix(JM_derotate_page_matrix(page))
else:
return JM_py_from_matrix(mupdf.FzMatrix())
@staticmethod
def _fill_widget(annot, widget):
val = JM_get_widget_properties(annot, widget)
widget.rect = Rect(annot.rect)
widget.xref = annot.xref
widget.parent = annot.parent
widget._annot = annot # backpointer to annot object
if not widget.script:
widget.script = None
if not widget.script_stroke:
widget.script_stroke = None
if not widget.script_format:
widget.script_format = None
if not widget.script_change:
widget.script_change = None
if not widget.script_calc:
widget.script_calc = None
if not widget.script_blur:
widget.script_blur = None
if not widget.script_focus:
widget.script_focus = None
return val
@staticmethod
def _get_all_contents(page):
page = _as_pdf_page(page.this)
res = JM_read_contents(page.obj())
result = JM_BinFromBuffer( res)
return result
@staticmethod
def _insert_contents(page, newcont, overlay=1):
"""Add bytes as a new /Contents object for a page, and return its xref."""
pdfpage = _as_pdf_page(page, required=1)
contbuf = JM_BufferFromBytes(newcont)
xref = JM_insert_contents(pdfpage.doc(), pdfpage.obj(), contbuf, overlay)
#fixme: pdfpage->doc->dirty = 1;
return xref
@staticmethod
def _le_annot_parms(annot, p1, p2, fill_color):
"""Get common parameters for making annot line end symbols.
Returns:
m: matrix that maps p1, p2 to points L, P on the x-axis
im: its inverse
L, P: transformed p1, p2
w: line width
scol: stroke color string
fcol: fill color store_shrink
opacity: opacity string (gs command)
"""
w = annot.border["width"] # line width
sc = annot.colors["stroke"] # stroke color
if not sc: # black if missing
sc = (0,0,0)
scol = " ".join(map(str, sc)) + " RG\n"
if fill_color:
fc = fill_color
else:
fc = annot.colors["fill"] # fill color
if not fc:
fc = (1,1,1) # white if missing
fcol = " ".join(map(str, fc)) + " rg\n"
# nr = annot.rect
np1 = p1 # point coord relative to annot rect
np2 = p2 # point coord relative to annot rect
m = Matrix(util_hor_matrix(np1, np2)) # matrix makes the line horizontal
im = ~m # inverted matrix
L = np1 * m # converted start (left) point
R = np2 * m # converted end (right) point
if 0 <= annot.opacity < 1:
opacity = "/H gs\n"
else:
opacity = ""
return m, im, L, R, w, scol, fcol, opacity
@staticmethod
def _le_butt(annot, p1, p2, lr, fill_color):
"""Make stream commands for butt line end symbol. "lr" denotes left (False) or right point.
"""
m, im, L, R, w, scol, fcol, opacity = TOOLS._le_annot_parms(annot, p1, p2, fill_color)
shift = 3
d = shift * max(1, w)
M = R if lr else L
top = (M + (0, -d/2.)) * im
bot = (M + (0, d/2.)) * im
ap = "\nq\n%s%f %f m\n" % (opacity, top.x, top.y)
ap += "%f %f l\n" % (bot.x, bot.y)
ap += _format_g(w) + " w\n"
ap += scol + "s\nQ\n"
return ap
@staticmethod
def _le_circle(annot, p1, p2, lr, fill_color):
"""Make stream commands for circle line end symbol. "lr" denotes left (False) or right point.
"""
m, im, L, R, w, scol, fcol, opacity = TOOLS._le_annot_parms(annot, p1, p2, fill_color)
shift = 2.5 # 2*shift*width = length of square edge
d = shift * max(1, w)
M = R - (d/2., 0) if lr else L + (d/2., 0)
r = Rect(M, M) + (-d, -d, d, d) # the square
ap = "q\n" + opacity + TOOLS._oval_string(r.tl * im, r.tr * im, r.br * im, r.bl * im)
ap += _format_g(w) + " w\n"
ap += scol + fcol + "b\nQ\n"
return ap
@staticmethod
def _le_closedarrow(annot, p1, p2, lr, fill_color):
"""Make stream commands for closed arrow line end symbol. "lr" denotes left (False) or right point.
"""
m, im, L, R, w, scol, fcol, opacity = TOOLS._le_annot_parms(annot, p1, p2, fill_color)
shift = 2.5
d = shift * max(1, w)
p2 = R + (d/2., 0) if lr else L - (d/2., 0)
p1 = p2 + (-2*d, -d) if lr else p2 + (2*d, -d)
p3 = p2 + (-2*d, d) if lr else p2 + (2*d, d)
p1 *= im
p2 *= im
p3 *= im
ap = "\nq\n%s%f %f m\n" % (opacity, p1.x, p1.y)
ap += "%f %f l\n" % (p2.x, p2.y)
ap += "%f %f l\n" % (p3.x, p3.y)
ap += _format_g(w) + " w\n"
ap += scol + fcol + "b\nQ\n"
return ap
@staticmethod
def _le_diamond(annot, p1, p2, lr, fill_color):
"""Make stream commands for diamond line end symbol. "lr" denotes left (False) or right point.
"""
m, im, L, R, w, scol, fcol, opacity = TOOLS._le_annot_parms(annot, p1, p2, fill_color)
shift = 2.5 # 2*shift*width = length of square edge
d = shift * max(1, w)
M = R - (d/2., 0) if lr else L + (d/2., 0)
r = Rect(M, M) + (-d, -d, d, d) # the square
# the square makes line longer by (2*shift - 1)*width
p = (r.tl + (r.bl - r.tl) * 0.5) * im
ap = "q\n%s%f %f m\n" % (opacity, p.x, p.y)
p = (r.tl + (r.tr - r.tl) * 0.5) * im
ap += "%f %f l\n" % (p.x, p.y)
p = (r.tr + (r.br - r.tr) * 0.5) * im
ap += "%f %f l\n" % (p.x, p.y)
p = (r.br + (r.bl - r.br) * 0.5) * im
ap += "%f %f l\n" % (p.x, p.y)
ap += _format_g(w) + " w\n"
ap += scol + fcol + "b\nQ\n"
return ap
@staticmethod
def _le_openarrow(annot, p1, p2, lr, fill_color):
"""Make stream commands for open arrow line end symbol. "lr" denotes left (False) or right point.
"""
m, im, L, R, w, scol, fcol, opacity = TOOLS._le_annot_parms(annot, p1, p2, fill_color)
shift = 2.5
d = shift * max(1, w)
p2 = R + (d/2., 0) if lr else L - (d/2., 0)
p1 = p2 + (-2*d, -d) if lr else p2 + (2*d, -d)
p3 = p2 + (-2*d, d) if lr else p2 + (2*d, d)
p1 *= im
p2 *= im
p3 *= im
ap = "\nq\n%s%f %f m\n" % (opacity, p1.x, p1.y)
ap += "%f %f l\n" % (p2.x, p2.y)
ap += "%f %f l\n" % (p3.x, p3.y)
ap += _format_g(w) + " w\n"
ap += scol + "S\nQ\n"
return ap
@staticmethod
def _le_rclosedarrow(annot, p1, p2, lr, fill_color):
"""Make stream commands for right closed arrow line end symbol. "lr" denotes left (False) or right point.
"""
m, im, L, R, w, scol, fcol, opacity = TOOLS._le_annot_parms(annot, p1, p2, fill_color)
shift = 2.5
d = shift * max(1, w)
p2 = R - (2*d, 0) if lr else L + (2*d, 0)
p1 = p2 + (2*d, -d) if lr else p2 + (-2*d, -d)
p3 = p2 + (2*d, d) if lr else p2 + (-2*d, d)
p1 *= im
p2 *= im
p3 *= im
ap = "\nq\n%s%f %f m\n" % (opacity, p1.x, p1.y)
ap += "%f %f l\n" % (p2.x, p2.y)
ap += "%f %f l\n" % (p3.x, p3.y)
ap += _format_g(w) + " w\n"
ap += scol + fcol + "b\nQ\n"
return ap
@staticmethod
def _le_ropenarrow(annot, p1, p2, lr, fill_color):
"""Make stream commands for right open arrow line end symbol. "lr" denotes left (False) or right point.
"""
m, im, L, R, w, scol, fcol, opacity = TOOLS._le_annot_parms(annot, p1, p2, fill_color)
shift = 2.5
d = shift * max(1, w)
p2 = R - (d/3., 0) if lr else L + (d/3., 0)
p1 = p2 + (2*d, -d) if lr else p2 + (-2*d, -d)
p3 = p2 + (2*d, d) if lr else p2 + (-2*d, d)
p1 *= im
p2 *= im
p3 *= im
ap = "\nq\n%s%f %f m\n" % (opacity, p1.x, p1.y)
ap += "%f %f l\n" % (p2.x, p2.y)
ap += "%f %f l\n" % (p3.x, p3.y)
ap += _format_g(w) + " w\n"
ap += scol + fcol + "S\nQ\n"
return ap
@staticmethod
def _le_slash(annot, p1, p2, lr, fill_color):
"""Make stream commands for slash line end symbol. "lr" denotes left (False) or right point.
"""
m, im, L, R, w, scol, fcol, opacity = TOOLS._le_annot_parms(annot, p1, p2, fill_color)
rw = 1.1547 * max(1, w) * 1.0 # makes rect diagonal a 30 deg inclination
M = R if lr else L
r = Rect(M.x - rw, M.y - 2 * w, M.x + rw, M.y + 2 * w)
top = r.tl * im
bot = r.br * im
ap = "\nq\n%s%f %f m\n" % (opacity, top.x, top.y)
ap += "%f %f l\n" % (bot.x, bot.y)
ap += _format_g(w) + " w\n"
ap += scol + "s\nQ\n"
return ap
@staticmethod
def _le_square(annot, p1, p2, lr, fill_color):
"""Make stream commands for square line end symbol. "lr" denotes left (False) or right point.
"""
m, im, L, R, w, scol, fcol, opacity = TOOLS._le_annot_parms(annot, p1, p2, fill_color)
shift = 2.5 # 2*shift*width = length of square edge
d = shift * max(1, w)
M = R - (d/2., 0) if lr else L + (d/2., 0)
r = Rect(M, M) + (-d, -d, d, d) # the square
# the square makes line longer by (2*shift - 1)*width
p = r.tl * im
ap = "q\n%s%f %f m\n" % (opacity, p.x, p.y)
p = r.tr * im
ap += "%f %f l\n" % (p.x, p.y)
p = r.br * im
ap += "%f %f l\n" % (p.x, p.y)
p = r.bl * im
ap += "%f %f l\n" % (p.x, p.y)
ap += _format_g(w) + " w\n"
ap += scol + fcol + "b\nQ\n"
return ap
@staticmethod
def _oval_string(p1, p2, p3, p4):
"""Return /AP string defining an oval within a 4-polygon provided as points
"""
def bezier(p, q, r):
f = "%f %f %f %f %f %f c\n"
return f % (p.x, p.y, q.x, q.y, r.x, r.y)
kappa = 0.55228474983 # magic number
ml = p1 + (p4 - p1) * 0.5 # middle points ...
mo = p1 + (p2 - p1) * 0.5 # for each ...
mr = p2 + (p3 - p2) * 0.5 # polygon ...
mu = p4 + (p3 - p4) * 0.5 # side
ol1 = ml + (p1 - ml) * kappa # the 8 bezier
ol2 = mo + (p1 - mo) * kappa # helper points
or1 = mo + (p2 - mo) * kappa
or2 = mr + (p2 - mr) * kappa
ur1 = mr + (p3 - mr) * kappa
ur2 = mu + (p3 - mu) * kappa
ul1 = mu + (p4 - mu) * kappa
ul2 = ml + (p4 - ml) * kappa
# now draw, starting from middle point of left side
ap = "%f %f m\n" % (ml.x, ml.y)
ap += bezier(ol1, ol2, mo)
ap += bezier(or1, or2, mr)
ap += bezier(ur1, ur2, mu)
ap += bezier(ul1, ul2, ml)
return ap
@staticmethod
def _parse_da(annot):
if g_use_extra:
val = extra.Tools_parse_da( annot.this)
else:
def Tools__parse_da(annot):
this_annot = annot.this
assert isinstance(this_annot, mupdf.PdfAnnot)
this_annot_obj = mupdf.pdf_annot_obj( this_annot)
pdf = mupdf.pdf_get_bound_document( this_annot_obj)
try:
da = mupdf.pdf_dict_get_inheritable( this_annot_obj, PDF_NAME('DA'))
if not da.m_internal:
trailer = mupdf.pdf_trailer(pdf)
da = mupdf.pdf_dict_getl(trailer,
PDF_NAME('Root'),
PDF_NAME('AcroForm'),
PDF_NAME('DA'),
)
da_str = mupdf.pdf_to_text_string(da)
except Exception:
if g_exceptions_verbose: exception_info()
return
return da_str
val = Tools__parse_da(annot)
if not val:
return ((0,), "", 0)
font = "Helv"
fsize = 12
col = (0, 0, 0)
dat = val.split() # split on any whitespace
for i, item in enumerate(dat):
if item == "Tf":
font = dat[i - 2][1:]
fsize = float(dat[i - 1])
dat[i] = dat[i-1] = dat[i-2] = ""
continue
if item == "g": # unicolor text
col = [(float(dat[i - 1]))]
dat[i] = dat[i-1] = ""
continue
if item == "rg": # RGB colored text
col = [float(f) for f in dat[i - 3:i]]
dat[i] = dat[i-1] = dat[i-2] = dat[i-3] = ""
continue
if item == "k": # CMYK colored text
col = [float(f) for f in dat[i - 4:i]]
dat[i] = dat[i-1] = dat[i-2] = dat[i-3] = dat[i-4] = ""
continue
val = (col, font, fsize)
return val
@staticmethod
def _reset_widget(annot):
this_annot = annot
this_annot_obj = mupdf.pdf_annot_obj(this_annot)
pdf = mupdf.pdf_get_bound_document(this_annot_obj)
mupdf.pdf_field_reset(pdf, this_annot_obj)
@staticmethod
def _rotate_matrix(page):
pdfpage = page._pdf_page(required=False)
if not pdfpage.m_internal:
return JM_py_from_matrix(mupdf.FzMatrix())
return JM_py_from_matrix(JM_rotate_page_matrix(pdfpage))
@staticmethod
def _save_widget(annot, widget):
JM_set_widget_properties(annot, widget)
def _update_da(annot, da_str):
if g_use_extra:
extra.Tools_update_da( annot.this, da_str)
else:
try:
this_annot = annot.this
assert isinstance(this_annot, mupdf.PdfAnnot)
mupdf.pdf_dict_put_text_string(mupdf.pdf_annot_obj(this_annot), PDF_NAME('DA'), da_str)
mupdf.pdf_dict_del(mupdf.pdf_annot_obj(this_annot), PDF_NAME('DS')) # /* not supported */
mupdf.pdf_dict_del(mupdf.pdf_annot_obj(this_annot), PDF_NAME('RC')) # /* not supported */
except Exception:
if g_exceptions_verbose: exception_info()
return
return
@staticmethod
def gen_id():
global TOOLS_JM_UNIQUE_ID
TOOLS_JM_UNIQUE_ID += 1
return TOOLS_JM_UNIQUE_ID
@staticmethod
def glyph_cache_empty():
'''
Empty the glyph cache.
'''
mupdf.fz_purge_glyph_cache()
@staticmethod
def image_profile(stream, keep_image=0):
'''
Metadata of an image binary stream.
'''
return JM_image_profile(stream, keep_image)
@staticmethod
def mupdf_display_errors(on=None):
'''
Set MuPDF error display to True or False.
'''
global JM_mupdf_show_errors
if on is not None:
JM_mupdf_show_errors = bool(on)
return JM_mupdf_show_errors
@staticmethod
def mupdf_display_warnings(on=None):
'''
Set MuPDF warnings display to True or False.
'''
global JM_mupdf_show_warnings
if on is not None:
JM_mupdf_show_warnings = bool(on)
return JM_mupdf_show_warnings
@staticmethod
def mupdf_version():
'''Get version of MuPDF binary build.'''
return mupdf.FZ_VERSION
@staticmethod
def mupdf_warnings(reset=1):
'''
Get the MuPDF warnings/errors with optional reset (default).
'''
# Get any trailing `... repeated <N> times...` message.
mupdf.fz_flush_warnings()
ret = '\n'.join( JM_mupdf_warnings_store)
if reset:
TOOLS.reset_mupdf_warnings()
return ret
@staticmethod
def reset_mupdf_warnings():
global JM_mupdf_warnings_store
JM_mupdf_warnings_store = list()
@staticmethod
def set_aa_level(level):
'''
Set anti-aliasing level.
'''
mupdf.fz_set_aa_level(level)
@staticmethod
def set_annot_stem( stem=None):
global JM_annot_id_stem
if stem is None:
return JM_annot_id_stem
len_ = len(stem) + 1
if len_ > 50:
len_ = 50
JM_annot_id_stem = stem[:50]
return JM_annot_id_stem
@staticmethod
def set_font_width(doc, xref, width):
pdf = _as_pdf_document(doc, required=0)
if not pdf.m_internal:
return False
font = mupdf.pdf_load_object(pdf, xref)
dfonts = mupdf.pdf_dict_get(font, PDF_NAME('DescendantFonts'))
if mupdf.pdf_is_array(dfonts):
n = mupdf.pdf_array_len(dfonts)
for i in range(n):
dfont = mupdf.pdf_array_get(dfonts, i)
warray = mupdf.pdf_new_array(pdf, 3)
mupdf.pdf_array_push(warray, mupdf.pdf_new_int(0))
mupdf.pdf_array_push(warray, mupdf.pdf_new_int(65535))
mupdf.pdf_array_push(warray, mupdf.pdf_new_int(width))
mupdf.pdf_dict_put(dfont, PDF_NAME('W'), warray)
return True
@staticmethod
def set_graphics_min_line_width(min_line_width):
'''
Set the graphics minimum line width.
'''
mupdf.fz_set_graphics_min_line_width(min_line_width)
@staticmethod
def set_icc( on=0):
"""Set ICC color handling on or off."""
if on:
if mupdf.FZ_ENABLE_ICC:
mupdf.fz_enable_icc()
else:
RAISEPY( "MuPDF built w/o ICC support",PyExc_ValueError)
elif mupdf.FZ_ENABLE_ICC:
mupdf.fz_disable_icc()
@staticmethod
def set_low_memory( on=None):
"""Set / unset MuPDF device caching."""
if on is not None:
_globals.no_device_caching = bool(on)
return _globals.no_device_caching
@staticmethod
def set_small_glyph_heights(on=None):
"""Set / unset small glyph heights."""
if on is not None:
_globals.small_glyph_heights = bool(on)
if g_use_extra:
extra.set_small_glyph_heights(_globals.small_glyph_heights)
return _globals.small_glyph_heights
@staticmethod
def set_subset_fontnames(on=None):
'''
Set / unset returning fontnames with their subset prefix.
'''
if on is not None:
_globals.subset_fontnames = bool(on)
if g_use_extra:
extra.set_subset_fontnames(_globals.subset_fontnames)
return _globals.subset_fontnames
@staticmethod
def show_aa_level():
'''
Show anti-aliasing values.
'''
return dict(
graphics = mupdf.fz_graphics_aa_level(),
text = mupdf.fz_text_aa_level(),
graphics_min_line_width = mupdf.fz_graphics_min_line_width(),
)
@staticmethod
def store_maxsize():
'''
MuPDF store size limit.
'''
# fixme: return gctx->store->max.
return None
@staticmethod
def store_shrink(percent):
'''
Free 'percent' of current store size.
'''
if percent >= 100:
mupdf.fz_empty_store()
return 0
if percent > 0:
mupdf.fz_shrink_store( 100 - percent)
# fixme: return gctx->store->size.
@staticmethod
def store_size():
'''
MuPDF current store size.
'''
# fixme: return gctx->store->size.
return None
@staticmethod
def unset_quad_corrections(on=None):
'''
Set ascender / descender corrections on or off.
'''
if on is not None:
_globals.skip_quad_corrections = bool(on)
if g_use_extra:
extra.set_skip_quad_corrections(_globals.skip_quad_corrections)
return _globals.skip_quad_corrections
# fixme: also defined at top-level.
JM_annot_id_stem = 'fitz'
fitz_config = JM_fitz_config()
# We cannot import utils earlier because it imports this .py file itself and
# uses some pymupdf.* types in function typing.
#
from . import utils
pdfcolor = dict(
[
(k, (r / 255, g / 255, b / 255))
for k, (r, g, b) in utils.getColorInfoDict().items()
]
)
# Callbacks not yet supported with cppyy.
if not mupdf_cppyy:
mupdf.fz_set_warning_callback(JM_mupdf_warning)
mupdf.fz_set_error_callback(JM_mupdf_error)
# If there are pending warnings when we exit, we end up in this sequence:
#
# atexit()
# -> mupdf::internal_thread_state::~internal_thread_state()
# -> fz_drop_context()
# -> fz_flush_warnings()
# -> SWIG Director code
# -> Python calling JM_mupdf_warning().
#
# Unfortunately this causes a SEGV, seemingly because the SWIG Director code has
# already been torn down.
#
# So we use a Python atexit handler to explicitly call fz_flush_warnings();
# this appears to happen early enough for the Director machinery to still
# work. So in the sequence above, fz_flush_warnings() will find that there are
# no pending warnings and will not attempt to call JM_mupdf_warning().
#
def _atexit():
#log( 'PyMuPDF/src/__init__.py:_atexit() called')
mupdf.fz_flush_warnings()
mupdf.fz_set_warning_callback(None)
mupdf.fz_set_error_callback(None)
#log( '_atexit() returning')
atexit.register( _atexit)
# Use utils.*() fns for some class methods.
#
recover_bbox_quad = utils.recover_bbox_quad
recover_char_quad = utils.recover_char_quad
recover_line_quad = utils.recover_line_quad
recover_quad = utils.recover_quad
recover_span_quad = utils.recover_span_quad
Annot.get_text = utils.get_text
Annot.get_textbox = utils.get_textbox
Document._do_links = utils.do_links
Document.del_toc_item = utils.del_toc_item
Document.get_char_widths = utils.get_char_widths
Document.get_oc = utils.get_oc
Document.get_ocmd = utils.get_ocmd
Document.get_page_labels = utils.get_page_labels
Document.get_page_numbers = utils.get_page_numbers
Document.get_page_pixmap = utils.get_page_pixmap
Document.get_page_text = utils.get_page_text
Document.get_toc = utils.get_toc
Document.has_annots = utils.has_annots
Document.has_links = utils.has_links
Document.insert_page = utils.insert_page
Document.new_page = utils.new_page
Document.scrub = utils.scrub
Document.search_page_for = utils.search_page_for
Document.set_metadata = utils.set_metadata
Document.set_oc = utils.set_oc
Document.set_ocmd = utils.set_ocmd
Document.set_page_labels = utils.set_page_labels
Document.set_toc = utils.set_toc
Document.set_toc_item = utils.set_toc_item
Document.subset_fonts = utils.subset_fonts
Document.tobytes = Document.write
Document.xref_copy = utils.xref_copy
IRect.get_area = utils.get_area
Page.apply_redactions = utils.apply_redactions
Page.delete_image = utils.delete_image
Page.delete_widget = utils.delete_widget
Page.draw_bezier = utils.draw_bezier
Page.draw_circle = utils.draw_circle
Page.draw_curve = utils.draw_curve
Page.draw_line = utils.draw_line
Page.draw_oval = utils.draw_oval
Page.draw_polyline = utils.draw_polyline
Page.draw_quad = utils.draw_quad
Page.draw_rect = utils.draw_rect
Page.draw_sector = utils.draw_sector
Page.draw_squiggle = utils.draw_squiggle
Page.draw_zigzag = utils.draw_zigzag
Page.get_image_info = utils.get_image_info
Page.get_image_rects = utils.get_image_rects
Page.get_label = utils.get_label
Page.get_links = utils.get_links
Page.get_pixmap = utils.get_pixmap
Page.get_text = utils.get_text
Page.get_text_blocks = utils.get_text_blocks
Page.get_text_selection = utils.get_text_selection
Page.get_text_words = utils.get_text_words
Page.get_textbox = utils.get_textbox
Page.get_textpage_ocr = utils.get_textpage_ocr
Page.insert_image = utils.insert_image
Page.insert_link = utils.insert_link
Page.insert_text = utils.insert_text
Page.insert_textbox = utils.insert_textbox
Page.insert_htmlbox = utils.insert_htmlbox
Page.new_shape = lambda x: utils.Shape(x)
Page.replace_image = utils.replace_image
Page.search_for = utils.search_for
Page.show_pdf_page = utils.show_pdf_page
Page.update_link = utils.update_link
Page.write_text = utils.write_text
from .table import find_tables
Page.find_tables = find_tables
Rect.get_area = utils.get_area
TextWriter.fill_textbox = utils.fill_textbox
class FitzDeprecation(DeprecationWarning):
pass
def restore_aliases():
warnings.filterwarnings( "once", category=FitzDeprecation)
def showthis(msg, cat, filename, lineno, file=None, line=None):
text = warnings.formatwarning(msg, cat, filename, lineno, line=line)
s = text.find("FitzDeprecation")
if s < 0:
log(text)
return
text = text[s:].splitlines()[0][4:]
log(text)
warnings.showwarning = showthis
def _alias(class_, new_name, legacy_name=None):
'''
Adds an alias for a class_ or module item clled <class_>.<new>.
class_:
Class/module to modify; use None for the current module.
new_name:
String name of existing item, e.g. name of method.
legacy_name:
Name of legacy object to create in <class_>. If None, we generate
from <item> by removing underscores and capitalising the next
letter.
'''
if class_ is None:
class_ = sys.modules[__name__]
if not legacy_name:
legacy_name = ''
capitalise_next = False
for c in new_name:
if c == '_':
capitalise_next = True
elif capitalise_next:
legacy_name += c.upper()
capitalise_next = False
else:
legacy_name += c
new_object = getattr( class_, new_name)
assert not getattr( class_, legacy_name, None), f'class {class_} already has {legacy_name}'
if callable( new_object):
def deprecated_function( *args, **kwargs):
warnings.warn(
f'"{legacy_name=}" removed from {class_} after v1.19.0 - use "{new_name}".',
category=FitzDeprecation,
)
return new_object( *args, **kwargs)
setattr( class_, legacy_name, deprecated_function)
deprecated_function.__doc__ = (
f'*** Deprecated and removed in version after v1.19.0 - use "{new_name}". ***\n'
f'{new_object.__doc__}'
)
else:
setattr( class_, legacy_name, new_object)
_alias( Annot, 'get_file', 'fileGet')
_alias( Annot, 'get_pixmap')
_alias( Annot, 'get_sound', 'soundGet')
_alias( Annot, 'get_text')
_alias( Annot, 'get_textbox')
_alias( Annot, 'get_textpage', 'getTextPage')
_alias( Annot, 'line_ends')
_alias( Annot, 'set_blendmode', 'setBlendMode')
_alias( Annot, 'set_border')
_alias( Annot, 'set_colors')
_alias( Annot, 'set_flags')
_alias( Annot, 'set_info')
_alias( Annot, 'set_line_ends')
_alias( Annot, 'set_name')
_alias( Annot, 'set_oc', 'setOC')
_alias( Annot, 'set_opacity')
_alias( Annot, 'set_rect')
_alias( Annot, 'update_file', 'fileUpd')
_alias( DisplayList, 'get_pixmap')
_alias( DisplayList, 'get_textpage', 'getTextPage')
_alias( Document, 'chapter_count')
_alias( Document, 'chapter_page_count')
_alias( Document, 'convert_to_pdf', 'convertToPDF')
_alias( Document, 'copy_page')
_alias( Document, 'delete_page')
_alias( Document, 'delete_pages', 'deletePageRange')
_alias( Document, 'embfile_add', 'embeddedFileAdd')
_alias( Document, 'embfile_count', 'embeddedFileCount')
_alias( Document, 'embfile_del', 'embeddedFileDel')
_alias( Document, 'embfile_get', 'embeddedFileGet')
_alias( Document, 'embfile_info', 'embeddedFileInfo')
_alias( Document, 'embfile_names', 'embeddedFileNames')
_alias( Document, 'embfile_upd', 'embeddedFileUpd')
_alias( Document, 'extract_font')
_alias( Document, 'extract_image')
_alias( Document, 'find_bookmark')
_alias( Document, 'fullcopy_page')
_alias( Document, 'get_char_widths')
_alias( Document, 'get_ocgs', 'getOCGs')
_alias( Document, 'get_page_fonts', 'getPageFontList')
_alias( Document, 'get_page_images', 'getPageImageList')
_alias( Document, 'get_page_pixmap')
_alias( Document, 'get_page_text')
_alias( Document, 'get_page_xobjects', 'getPageXObjectList')
_alias( Document, 'get_sigflags', 'getSigFlags')
_alias( Document, 'get_toc', 'getToC')
_alias( Document, 'get_xml_metadata')
_alias( Document, 'insert_page')
_alias( Document, 'insert_pdf', 'insertPDF')
_alias( Document, 'is_dirty')
_alias( Document, 'is_form_pdf', 'isFormPDF')
_alias( Document, 'is_pdf', 'isPDF')
_alias( Document, 'is_reflowable')
_alias( Document, 'is_repaired')
_alias( Document, 'last_location')
_alias( Document, 'load_page')
_alias( Document, 'make_bookmark')
_alias( Document, 'move_page')
_alias( Document, 'needs_pass')
_alias( Document, 'new_page')
_alias( Document, 'next_location')
_alias( Document, 'page_count')
_alias( Document, 'page_cropbox', 'pageCropBox')
_alias( Document, 'page_xref')
_alias( Document, 'pdf_catalog', 'PDFCatalog')
_alias( Document, 'pdf_trailer', 'PDFTrailer')
_alias( Document, 'prev_location', 'previousLocation')
_alias( Document, 'resolve_link')
_alias( Document, 'search_page_for')
_alias( Document, 'set_language')
_alias( Document, 'set_metadata')
_alias( Document, 'set_toc', 'setToC')
_alias( Document, 'set_xml_metadata')
_alias( Document, 'update_object')
_alias( Document, 'update_stream')
_alias( Document, 'xref_is_stream', 'isStream')
_alias( Document, 'xref_length')
_alias( Document, 'xref_object')
_alias( Document, 'xref_stream')
_alias( Document, 'xref_stream_raw')
_alias( Document, 'xref_xml_metadata', 'metadataXML')
_alias( IRect, 'get_area')
_alias( IRect, 'get_area', 'getRectArea')
_alias( IRect, 'include_point')
_alias( IRect, 'include_rect')
_alias( IRect, 'is_empty')
_alias( IRect, 'is_infinite')
_alias( Link, 'is_external')
_alias( Link, 'set_border')
_alias( Link, 'set_colors')
_alias( Matrix, 'is_rectilinear')
_alias( Matrix, 'prerotate', 'preRotate')
_alias( Matrix, 'prescale', 'preScale')
_alias( Matrix, 'preshear', 'preShear')
_alias( Matrix, 'pretranslate', 'preTranslate')
_alias( None, 'get_pdf_now', 'getPDFnow')
_alias( None, 'get_pdf_str', 'getPDFstr')
_alias( None, 'get_text_length')
_alias( None, 'get_text_length', 'getTextlength')
_alias( None, 'image_profile', 'ImageProperties')
_alias( None, 'paper_rect', 'PaperRect')
_alias( None, 'paper_size', 'PaperSize')
_alias( None, 'paper_sizes')
_alias( None, 'planish_line')
_alias( Outline, 'is_external')
_alias( Outline, 'is_open')
_alias( Page, 'add_caret_annot')
_alias( Page, 'add_circle_annot')
_alias( Page, 'add_file_annot')
_alias( Page, 'add_freetext_annot')
_alias( Page, 'add_highlight_annot')
_alias( Page, 'add_ink_annot')
_alias( Page, 'add_line_annot')
_alias( Page, 'add_polygon_annot')
_alias( Page, 'add_polyline_annot')
_alias( Page, 'add_rect_annot')
_alias( Page, 'add_redact_annot')
_alias( Page, 'add_squiggly_annot')
_alias( Page, 'add_stamp_annot')
_alias( Page, 'add_strikeout_annot')
_alias( Page, 'add_text_annot')
_alias( Page, 'add_underline_annot')
_alias( Page, 'add_widget')
_alias( Page, 'clean_contents')
_alias( Page, 'cropbox', 'CropBox')
_alias( Page, 'cropbox_position', 'CropBoxPosition')
_alias( Page, 'delete_annot')
_alias( Page, 'delete_link')
_alias( Page, 'delete_widget')
_alias( Page, 'derotation_matrix')
_alias( Page, 'draw_bezier')
_alias( Page, 'draw_circle')
_alias( Page, 'draw_curve')
_alias( Page, 'draw_line')
_alias( Page, 'draw_oval')
_alias( Page, 'draw_polyline')
_alias( Page, 'draw_quad')
_alias( Page, 'draw_rect')
_alias( Page, 'draw_sector')
_alias( Page, 'draw_squiggle')
_alias( Page, 'draw_zigzag')
_alias( Page, 'first_annot')
_alias( Page, 'first_link')
_alias( Page, 'first_widget')
_alias( Page, 'get_contents')
_alias( Page, 'get_displaylist', 'getDisplayList')
_alias( Page, 'get_drawings')
_alias( Page, 'get_fonts', 'getFontList')
_alias( Page, 'get_image_bbox')
_alias( Page, 'get_images', 'getImageList')
_alias( Page, 'get_links')
_alias( Page, 'get_pixmap')
_alias( Page, 'get_svg_image', 'getSVGimage')
_alias( Page, 'get_text')
_alias( Page, 'get_text_blocks')
_alias( Page, 'get_text_words')
_alias( Page, 'get_textbox')
_alias( Page, 'get_textpage', 'getTextPage')
_alias( Page, 'insert_font')
_alias( Page, 'insert_image')
_alias( Page, 'insert_link')
_alias( Page, 'insert_text')
_alias( Page, 'insert_textbox')
_alias( Page, 'is_wrapped', '_isWrapped')
_alias( Page, 'load_annot')
_alias( Page, 'load_links')
_alias( Page, 'mediabox', 'MediaBox')
_alias( Page, 'mediabox_size', 'MediaBoxSize')
_alias( Page, 'new_shape')
_alias( Page, 'read_contents')
_alias( Page, 'rotation_matrix')
_alias( Page, 'search_for')
_alias( Page, 'set_cropbox', 'setCropBox')
_alias( Page, 'set_mediabox', 'setMediaBox')
_alias( Page, 'set_rotation')
_alias( Page, 'show_pdf_page', 'showPDFpage')
_alias( Page, 'transformation_matrix')
_alias( Page, 'update_link')
_alias( Page, 'wrap_contents')
_alias( Page, 'write_text')
_alias( Pixmap, 'clear_with')
_alias( Pixmap, 'copy', 'copyPixmap')
_alias( Pixmap, 'gamma_with')
_alias( Pixmap, 'invert_irect', 'invertIRect')
_alias( Pixmap, 'pil_save', 'pillowWrite')
_alias( Pixmap, 'pil_tobytes', 'pillowData')
_alias( Pixmap, 'save', 'writeImage')
_alias( Pixmap, 'save', 'writePNG')
_alias( Pixmap, 'set_alpha')
_alias( Pixmap, 'set_dpi', 'setResolution')
_alias( Pixmap, 'set_origin')
_alias( Pixmap, 'set_pixel')
_alias( Pixmap, 'set_rect')
_alias( Pixmap, 'tint_with')
_alias( Pixmap, 'tobytes', 'getImageData')
_alias( Pixmap, 'tobytes', 'getPNGData')
_alias( Pixmap, 'tobytes', 'getPNGdata')
_alias( Quad, 'is_convex')
_alias( Quad, 'is_empty')
_alias( Quad, 'is_rectangular')
_alias( Rect, 'get_area')
_alias( Rect, 'get_area', 'getRectArea')
_alias( Rect, 'include_point')
_alias( Rect, 'include_rect')
_alias( Rect, 'is_empty')
_alias( Rect, 'is_infinite')
_alias( TextWriter, 'fill_textbox')
_alias( TextWriter, 'write_text')
_alias( utils.Shape, 'draw_bezier')
_alias( utils.Shape, 'draw_circle')
_alias( utils.Shape, 'draw_curve')
_alias( utils.Shape, 'draw_line')
_alias( utils.Shape, 'draw_oval')
_alias( utils.Shape, 'draw_polyline')
_alias( utils.Shape, 'draw_quad')
_alias( utils.Shape, 'draw_rect')
_alias( utils.Shape, 'draw_sector')
_alias( utils.Shape, 'draw_squiggle')
_alias( utils.Shape, 'draw_zigzag')
_alias( utils.Shape, 'insert_text')
_alias( utils.Shape, 'insert_textbox')
if 0:
restore_aliases()
__version__ = VersionBind
__doc__ = (
f'PyMuPDF {VersionBind}: Python bindings for the MuPDF {VersionFitz} library (rebased implementation).\n'
f'Python {sys.version_info[0]}.{sys.version_info[1]} running on {sys.platform} ({64 if sys.maxsize > 2**32 else 32}-bit).\n'
)
| 805,118 | Python | .py | 19,821 | 30.136673 | 173 | 0.558317 | pymupdf/PyMuPDF | 5,009 | 480 | 32 | AGPL-3.0 | 9/5/2024, 5:12:54 PM (Europe/Amsterdam) |
21,299 | table.py | pymupdf_PyMuPDF/src/table.py | """
Copyright (C) 2023 Artifex Software, Inc.
This file is part of PyMuPDF.
PyMuPDF is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
PyMuPDF is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License
along with MuPDF. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>
Alternative licensing terms are available from the licensor.
For commercial licensing, see <https://www.artifex.com/> or contact
Artifex Software, Inc., 39 Mesa Street, Suite 108A, San Francisco,
CA 94129, USA, for further information.
---------------------------------------------------------------------
Portions of this code have been ported from pdfplumber, see
https://pypi.org/project/pdfplumber/.
The ported code is under the following MIT license:
---------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015, Jeremy Singer-Vine
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---------------------------------------------------------------------
Also see here: https://github.com/jsvine/pdfplumber/blob/stable/LICENSE.txt
---------------------------------------------------------------------
The porting mainly pertains to files "table.py" and relevant parts of
"utils/text.py" within pdfplumber's repository on Github.
With respect to "text.py", we have removed functions or features that are not
used by table processing. Examples are:
* the text search function
* simple text extraction
* text extraction by lines
Original pdfplumber code does neither detect, nor identify table headers.
This PyMuPDF port adds respective code to the 'Table' class as method '_get_header'.
This is implemented as new class TableHeader with the properties:
* bbox: A tuple for the header's bbox
* cells: A tuple for each bbox of a column header
* names: A list of strings with column header text
* external: A bool indicating whether the header is outside the table cells.
"""
import inspect
import itertools
import string
import html
from collections.abc import Sequence
from dataclasses import dataclass
from operator import itemgetter
# -------------------------------------------------------------------
# Start of PyMuPDF interface code
# -------------------------------------------------------------------
from . import (
Rect,
Matrix,
TEXTFLAGS_TEXT,
TOOLS,
EMPTY_RECT,
sRGB_to_pdf,
Point,
message,
)
EDGES = [] # vector graphics from PyMuPDF
CHARS = [] # text characters from PyMuPDF
TEXTPAGE = None
white_spaces = set(string.whitespace) # for checking white space only cells
# -------------------------------------------------------------------
# End of PyMuPDF interface code
# -------------------------------------------------------------------
class UnsetFloat(float):
pass
NON_NEGATIVE_SETTINGS = [
"snap_tolerance",
"snap_x_tolerance",
"snap_y_tolerance",
"join_tolerance",
"join_x_tolerance",
"join_y_tolerance",
"edge_min_length",
"min_words_vertical",
"min_words_horizontal",
"intersection_tolerance",
"intersection_x_tolerance",
"intersection_y_tolerance",
]
TABLE_STRATEGIES = ["lines", "lines_strict", "text", "explicit"]
UNSET = UnsetFloat(0)
DEFAULT_SNAP_TOLERANCE = 3
DEFAULT_JOIN_TOLERANCE = 3
DEFAULT_MIN_WORDS_VERTICAL = 3
DEFAULT_MIN_WORDS_HORIZONTAL = 1
DEFAULT_X_TOLERANCE = 3
DEFAULT_Y_TOLERANCE = 3
DEFAULT_X_DENSITY = 7.25
DEFAULT_Y_DENSITY = 13
bbox_getter = itemgetter("x0", "top", "x1", "bottom")
LIGATURES = {
"ff": "ff",
"ffi": "ffi",
"ffl": "ffl",
"fi": "fi",
"fl": "fl",
"st": "st",
"ſt": "st",
}
def to_list(collection) -> list:
if isinstance(collection, list):
return collection
elif isinstance(collection, Sequence):
return list(collection)
elif hasattr(collection, "to_dict"):
res = collection.to_dict("records") # pragma: nocover
return res
else:
return list(collection)
class TextMap:
"""
A TextMap maps each unicode character in the text to an individual `char`
object (or, in the case of layout-implied whitespace, `None`).
"""
def __init__(self, tuples=None) -> None:
self.tuples = tuples
self.as_string = "".join(map(itemgetter(0), tuples))
def match_to_dict(
self,
m,
main_group: int = 0,
return_groups: bool = True,
return_chars: bool = True,
) -> dict:
subset = self.tuples[m.start(main_group) : m.end(main_group)]
chars = [c for (text, c) in subset if c is not None]
x0, top, x1, bottom = objects_to_bbox(chars)
result = {
"text": m.group(main_group),
"x0": x0,
"top": top,
"x1": x1,
"bottom": bottom,
}
if return_groups:
result["groups"] = m.groups()
if return_chars:
result["chars"] = chars
return result
class WordMap:
"""
A WordMap maps words->chars.
"""
def __init__(self, tuples) -> None:
self.tuples = tuples
def to_textmap(
self,
layout: bool = False,
layout_width=0,
layout_height=0,
layout_width_chars: int = 0,
layout_height_chars: int = 0,
x_density=DEFAULT_X_DENSITY,
y_density=DEFAULT_Y_DENSITY,
x_shift=0,
y_shift=0,
y_tolerance=DEFAULT_Y_TOLERANCE,
use_text_flow: bool = False,
presorted: bool = False,
expand_ligatures: bool = True,
) -> TextMap:
"""
Given a list of (word, chars) tuples (i.e., a WordMap), return a list of
(char-text, char) tuples (i.e., a TextMap) that can be used to mimic the
structural layout of the text on the page(s), using the following approach:
- Sort the words by (doctop, x0) if not already sorted.
- Calculate the initial doctop for the starting page.
- Cluster the words by doctop (taking `y_tolerance` into account), and
iterate through them.
- For each cluster, calculate the distance between that doctop and the
initial doctop, in points, minus `y_shift`. Divide that distance by
`y_density` to calculate the minimum number of newlines that should come
before this cluster. Append that number of newlines *minus* the number of
newlines already appended, with a minimum of one.
- Then for each cluster, iterate through each word in it. Divide each
word's x0, minus `x_shift`, by `x_density` to calculate the minimum
number of characters that should come before this cluster. Append that
number of spaces *minus* the number of characters and spaces already
appended, with a minimum of one. Then append the word's text.
- At the termination of each line, add more spaces if necessary to
mimic `layout_width`.
- Finally, add newlines to the end if necessary to mimic to
`layout_height`.
Note: This approach currently works best for horizontal, left-to-right
text, but will display all words regardless of orientation. There is room
for improvement in better supporting right-to-left text, as well as
vertical text.
"""
_textmap = []
if not len(self.tuples):
return TextMap(_textmap)
expansions = LIGATURES if expand_ligatures else {}
if layout:
if layout_width_chars:
if layout_width:
raise ValueError(
"`layout_width` and `layout_width_chars` cannot both be set."
)
else:
layout_width_chars = int(round(layout_width / x_density))
if layout_height_chars:
if layout_height:
raise ValueError(
"`layout_height` and `layout_height_chars` cannot both be set."
)
else:
layout_height_chars = int(round(layout_height / y_density))
blank_line = [(" ", None)] * layout_width_chars
else:
blank_line = []
num_newlines = 0
words_sorted_doctop = (
self.tuples
if presorted or use_text_flow
else sorted(self.tuples, key=lambda x: float(x[0]["doctop"]))
)
first_word = words_sorted_doctop[0][0]
doctop_start = first_word["doctop"] - first_word["top"]
for i, ws in enumerate(
cluster_objects(
words_sorted_doctop, lambda x: float(x[0]["doctop"]), y_tolerance
)
):
y_dist = (
(ws[0][0]["doctop"] - (doctop_start + y_shift)) / y_density
if layout
else 0
)
num_newlines_prepend = max(
# At least one newline, unless this iis the first line
int(i > 0),
# ... or as many as needed to get the imputed "distance" from the top
round(y_dist) - num_newlines,
)
for i in range(num_newlines_prepend):
if not len(_textmap) or _textmap[-1][0] == "\n":
_textmap += blank_line
_textmap.append(("\n", None))
num_newlines += num_newlines_prepend
line_len = 0
line_words_sorted_x0 = (
ws
if presorted or use_text_flow
else sorted(ws, key=lambda x: float(x[0]["x0"]))
)
for word, chars in line_words_sorted_x0:
x_dist = (word["x0"] - x_shift) / x_density if layout else 0
num_spaces_prepend = max(min(1, line_len), round(x_dist) - line_len)
_textmap += [(" ", None)] * num_spaces_prepend
line_len += num_spaces_prepend
for c in chars:
letters = expansions.get(c["text"], c["text"])
for letter in letters:
_textmap.append((letter, c))
line_len += 1
# Append spaces at end of line
if layout:
_textmap += [(" ", None)] * (layout_width_chars - line_len)
# Append blank lines at end of text
if layout:
num_newlines_append = layout_height_chars - (num_newlines + 1)
for i in range(num_newlines_append):
if i > 0:
_textmap += blank_line
_textmap.append(("\n", None))
# Remove terminal newline
if _textmap[-1] == ("\n", None):
_textmap = _textmap[:-1]
return TextMap(_textmap)
class WordExtractor:
def __init__(
self,
x_tolerance=DEFAULT_X_TOLERANCE,
y_tolerance=DEFAULT_Y_TOLERANCE,
keep_blank_chars: bool = False,
use_text_flow=False,
horizontal_ltr=True, # Should words be read left-to-right?
vertical_ttb=False, # Should vertical words be read top-to-bottom?
extra_attrs=None,
split_at_punctuation=False,
expand_ligatures=True,
):
self.x_tolerance = x_tolerance
self.y_tolerance = y_tolerance
self.keep_blank_chars = keep_blank_chars
self.use_text_flow = use_text_flow
self.horizontal_ltr = horizontal_ltr
self.vertical_ttb = vertical_ttb
self.extra_attrs = [] if extra_attrs is None else extra_attrs
# Note: string.punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
self.split_at_punctuation = (
string.punctuation
if split_at_punctuation is True
else (split_at_punctuation or "")
)
self.expansions = LIGATURES if expand_ligatures else {}
def merge_chars(self, ordered_chars: list):
x0, top, x1, bottom = objects_to_bbox(ordered_chars)
doctop_adj = ordered_chars[0]["doctop"] - ordered_chars[0]["top"]
upright = ordered_chars[0]["upright"]
direction = 1 if (self.horizontal_ltr if upright else self.vertical_ttb) else -1
matrix = ordered_chars[0]["matrix"]
rotation = 0
if not upright and matrix[1] < 0:
ordered_chars = reversed(ordered_chars)
rotation = 270
if matrix[0] < 0 and matrix[3] < 0:
rotation = 180
elif matrix[1] > 0:
rotation = 90
word = {
"text": "".join(
self.expansions.get(c["text"], c["text"]) for c in ordered_chars
),
"x0": x0,
"x1": x1,
"top": top,
"doctop": top + doctop_adj,
"bottom": bottom,
"upright": upright,
"direction": direction,
"rotation": rotation,
}
for key in self.extra_attrs:
word[key] = ordered_chars[0][key]
return word
def char_begins_new_word(
self,
prev_char,
curr_char,
) -> bool:
"""This method takes several factors into account to determine if
`curr_char` represents the beginning of a new word:
- Whether the text is "upright" (i.e., non-rotated)
- Whether the user has specified that horizontal text runs
left-to-right (default) or right-to-left, as represented by
self.horizontal_ltr
- Whether the user has specified that vertical text the text runs
top-to-bottom (default) or bottom-to-top, as represented by
self.vertical_ttb
- The x0, top, x1, and bottom attributes of prev_char and
curr_char
- The self.x_tolerance and self.y_tolerance settings. Note: In
this case, x/y refer to those directions for non-rotated text.
For vertical text, they are flipped. A more accurate terminology
might be "*intra*line character distance tolerance" and
"*inter*line character distance tolerance"
An important note: The *intra*line distance is measured from the
*end* of the previous character to the *beginning* of the current
character, while the *inter*line distance is measured from the
*top* of the previous character to the *top* of the next
character. The reasons for this are partly repository-historical,
and partly logical, as successive text lines' bounding boxes often
overlap slightly (and we don't want that overlap to be interpreted
as the two lines being the same line).
The upright-ness of the character determines the attributes to
compare, while horizontal_ltr/vertical_ttb determine the direction
of the comparison.
"""
# Note: Due to the grouping step earlier in the process,
# curr_char["upright"] will always equal prev_char["upright"].
if curr_char["upright"]:
x = self.x_tolerance
y = self.y_tolerance
ay = prev_char["top"]
cy = curr_char["top"]
if self.horizontal_ltr:
ax = prev_char["x0"]
bx = prev_char["x1"]
cx = curr_char["x0"]
else:
ax = -prev_char["x1"]
bx = -prev_char["x0"]
cx = -curr_char["x1"]
else:
x = self.y_tolerance
y = self.x_tolerance
ay = prev_char["x0"]
cy = curr_char["x0"]
if self.vertical_ttb:
ax = prev_char["top"]
bx = prev_char["bottom"]
cx = curr_char["top"]
else:
ax = -prev_char["bottom"]
bx = -prev_char["top"]
cx = -curr_char["bottom"]
return bool(
# Intraline test
(cx < ax)
or (cx > bx + x)
# Interline test
or (cy > ay + y)
)
def iter_chars_to_words(self, ordered_chars):
current_word: list = []
def start_next_word(new_char=None):
nonlocal current_word
if current_word:
yield current_word
current_word = [] if new_char is None else [new_char]
for char in ordered_chars:
text = char["text"]
if not self.keep_blank_chars and text.isspace():
yield from start_next_word(None)
elif text in self.split_at_punctuation:
yield from start_next_word(char)
yield from start_next_word(None)
elif current_word and self.char_begins_new_word(current_word[-1], char):
yield from start_next_word(char)
else:
current_word.append(char)
# Finally, after all chars processed
if current_word:
yield current_word
def iter_sort_chars(self, chars):
def upright_key(x) -> int:
return -int(x["upright"])
for upright_cluster in cluster_objects(list(chars), upright_key, 0):
upright = upright_cluster[0]["upright"]
cluster_key = "doctop" if upright else "x0"
# Cluster by line
subclusters = cluster_objects(
upright_cluster, itemgetter(cluster_key), self.y_tolerance
)
for sc in subclusters:
# Sort within line
sort_key = "x0" if upright else "doctop"
to_yield = sorted(sc, key=itemgetter(sort_key))
# Reverse order if necessary
if not (self.horizontal_ltr if upright else self.vertical_ttb):
yield from reversed(to_yield)
else:
yield from to_yield
def iter_extract_tuples(self, chars):
ordered_chars = chars if self.use_text_flow else self.iter_sort_chars(chars)
grouping_key = itemgetter("upright", *self.extra_attrs)
grouped_chars = itertools.groupby(ordered_chars, grouping_key)
for keyvals, char_group in grouped_chars:
for word_chars in self.iter_chars_to_words(char_group):
yield (self.merge_chars(word_chars), word_chars)
def extract_wordmap(self, chars) -> WordMap:
return WordMap(list(self.iter_extract_tuples(chars)))
def extract_words(self, chars: list) -> list:
words = list(word for word, word_chars in self.iter_extract_tuples(chars))
return words
def extract_words(chars: list, **kwargs) -> list:
return WordExtractor(**kwargs).extract_words(chars)
TEXTMAP_KWARGS = inspect.signature(WordMap.to_textmap).parameters.keys()
WORD_EXTRACTOR_KWARGS = inspect.signature(WordExtractor).parameters.keys()
def chars_to_textmap(chars: list, **kwargs) -> TextMap:
kwargs.update({"presorted": True})
extractor = WordExtractor(
**{k: kwargs[k] for k in WORD_EXTRACTOR_KWARGS if k in kwargs}
)
wordmap = extractor.extract_wordmap(chars)
textmap = wordmap.to_textmap(
**{k: kwargs[k] for k in TEXTMAP_KWARGS if k in kwargs}
)
return textmap
def extract_text(chars: list, **kwargs) -> str:
chars = to_list(chars)
if len(chars) == 0:
return ""
if kwargs.get("layout"):
return chars_to_textmap(chars, **kwargs).as_string
else:
y_tolerance = kwargs.get("y_tolerance", DEFAULT_Y_TOLERANCE)
extractor = WordExtractor(
**{k: kwargs[k] for k in WORD_EXTRACTOR_KWARGS if k in kwargs}
)
words = extractor.extract_words(chars)
if words:
rotation = words[0]["rotation"] # rotation cannot change within a cell
else:
rotation = 0
if rotation == 90:
words.sort(key=lambda w: (w["x1"], -w["top"]))
lines = " ".join([w["text"] for w in words])
elif rotation == 270:
words.sort(key=lambda w: (-w["x1"], w["top"]))
lines = " ".join([w["text"] for w in words])
else:
lines = cluster_objects(words, itemgetter("doctop"), y_tolerance)
lines = "\n".join(" ".join(word["text"] for word in line) for line in lines)
if rotation == 180: # needs extra treatment
lines = "".join([(c if c != "\n" else " ") for c in reversed(lines)])
return lines
def collate_line(
line_chars: list,
tolerance=DEFAULT_X_TOLERANCE,
) -> str:
coll = ""
last_x1 = None
for char in sorted(line_chars, key=itemgetter("x0")):
if (last_x1 is not None) and (char["x0"] > (last_x1 + tolerance)):
coll += " "
last_x1 = char["x1"]
coll += char["text"]
return coll
def dedupe_chars(chars: list, tolerance=1) -> list:
"""
Removes duplicate chars — those sharing the same text, fontname, size,
and positioning (within `tolerance`) as other characters in the set.
"""
key = itemgetter("fontname", "size", "upright", "text")
pos_key = itemgetter("doctop", "x0")
def yield_unique_chars(chars: list):
sorted_chars = sorted(chars, key=key)
for grp, grp_chars in itertools.groupby(sorted_chars, key=key):
for y_cluster in cluster_objects(
list(grp_chars), itemgetter("doctop"), tolerance
):
for x_cluster in cluster_objects(
y_cluster, itemgetter("x0"), tolerance
):
yield sorted(x_cluster, key=pos_key)[0]
deduped = yield_unique_chars(chars)
return sorted(deduped, key=chars.index)
def line_to_edge(line):
edge = dict(line)
edge["orientation"] = "h" if (line["top"] == line["bottom"]) else "v"
return edge
def rect_to_edges(rect) -> list:
top, bottom, left, right = [dict(rect) for x in range(4)]
top.update(
{
"object_type": "rect_edge",
"height": 0,
"y0": rect["y1"],
"bottom": rect["top"],
"orientation": "h",
}
)
bottom.update(
{
"object_type": "rect_edge",
"height": 0,
"y1": rect["y0"],
"top": rect["top"] + rect["height"],
"doctop": rect["doctop"] + rect["height"],
"orientation": "h",
}
)
left.update(
{
"object_type": "rect_edge",
"width": 0,
"x1": rect["x0"],
"orientation": "v",
}
)
right.update(
{
"object_type": "rect_edge",
"width": 0,
"x0": rect["x1"],
"orientation": "v",
}
)
return [top, bottom, left, right]
def curve_to_edges(curve) -> list:
point_pairs = zip(curve["pts"], curve["pts"][1:])
return [
{
"object_type": "curve_edge",
"x0": min(p0[0], p1[0]),
"x1": max(p0[0], p1[0]),
"top": min(p0[1], p1[1]),
"doctop": min(p0[1], p1[1]) + (curve["doctop"] - curve["top"]),
"bottom": max(p0[1], p1[1]),
"width": abs(p0[0] - p1[0]),
"height": abs(p0[1] - p1[1]),
"orientation": "v" if p0[0] == p1[0] else ("h" if p0[1] == p1[1] else None),
}
for p0, p1 in point_pairs
]
def obj_to_edges(obj) -> list:
t = obj["object_type"]
if "_edge" in t:
return [obj]
elif t == "line":
return [line_to_edge(obj)]
else:
return {"rect": rect_to_edges, "curve": curve_to_edges}[t](obj)
def filter_edges(
edges,
orientation=None,
edge_type=None,
min_length=1,
) -> list:
if orientation not in ("v", "h", None):
raise ValueError("Orientation must be 'v' or 'h'")
def test(e) -> bool:
dim = "height" if e["orientation"] == "v" else "width"
et_correct = e["object_type"] == edge_type if edge_type is not None else True
orient_correct = orientation is None or e["orientation"] == orientation
return bool(et_correct and orient_correct and (e[dim] >= min_length))
return list(filter(test, edges))
def cluster_list(xs, tolerance=0) -> list:
if tolerance == 0:
return [[x] for x in sorted(xs)]
if len(xs) < 2:
return [[x] for x in sorted(xs)]
groups = []
xs = list(sorted(xs))
current_group = [xs[0]]
last = xs[0]
for x in xs[1:]:
if x <= (last + tolerance):
current_group.append(x)
else:
groups.append(current_group)
current_group = [x]
last = x
groups.append(current_group)
return groups
def make_cluster_dict(values, tolerance) -> dict:
clusters = cluster_list(list(set(values)), tolerance)
nested_tuples = [
[(val, i) for val in value_cluster] for i, value_cluster in enumerate(clusters)
]
return dict(itertools.chain(*nested_tuples))
def cluster_objects(xs, key_fn, tolerance) -> list:
if not callable(key_fn):
key_fn = itemgetter(key_fn)
values = map(key_fn, xs)
cluster_dict = make_cluster_dict(values, tolerance)
get_0, get_1 = itemgetter(0), itemgetter(1)
cluster_tuples = sorted(((x, cluster_dict.get(key_fn(x))) for x in xs), key=get_1)
grouped = itertools.groupby(cluster_tuples, key=get_1)
return [list(map(get_0, v)) for k, v in grouped]
def move_object(obj, axis: str, value):
assert axis in ("h", "v")
if axis == "h":
new_items = [
("x0", obj["x0"] + value),
("x1", obj["x1"] + value),
]
if axis == "v":
new_items = [
("top", obj["top"] + value),
("bottom", obj["bottom"] + value),
]
if "doctop" in obj:
new_items += [("doctop", obj["doctop"] + value)]
if "y0" in obj:
new_items += [
("y0", obj["y0"] - value),
("y1", obj["y1"] - value),
]
return obj.__class__(tuple(obj.items()) + tuple(new_items))
def snap_objects(objs, attr: str, tolerance) -> list:
axis = {"x0": "h", "x1": "h", "top": "v", "bottom": "v"}[attr]
list_objs = list(objs)
clusters = cluster_objects(list_objs, itemgetter(attr), tolerance)
avgs = [sum(map(itemgetter(attr), cluster)) / len(cluster) for cluster in clusters]
snapped_clusters = [
[move_object(obj, axis, avg - obj[attr]) for obj in cluster]
for cluster, avg in zip(clusters, avgs)
]
return list(itertools.chain(*snapped_clusters))
def snap_edges(
edges,
x_tolerance=DEFAULT_SNAP_TOLERANCE,
y_tolerance=DEFAULT_SNAP_TOLERANCE,
):
"""
Given a list of edges, snap any within `tolerance` pixels of one another
to their positional average.
"""
by_orientation = {"v": [], "h": []}
for e in edges:
by_orientation[e["orientation"]].append(e)
snapped_v = snap_objects(by_orientation["v"], "x0", x_tolerance)
snapped_h = snap_objects(by_orientation["h"], "top", y_tolerance)
return snapped_v + snapped_h
def resize_object(obj, key: str, value):
assert key in ("x0", "x1", "top", "bottom")
old_value = obj[key]
diff = value - old_value
new_items = [
(key, value),
]
if key == "x0":
assert value <= obj["x1"]
new_items.append(("width", obj["x1"] - value))
elif key == "x1":
assert value >= obj["x0"]
new_items.append(("width", value - obj["x0"]))
elif key == "top":
assert value <= obj["bottom"]
new_items.append(("doctop", obj["doctop"] + diff))
new_items.append(("height", obj["height"] - diff))
if "y1" in obj:
new_items.append(("y1", obj["y1"] - diff))
elif key == "bottom":
assert value >= obj["top"]
new_items.append(("height", obj["height"] + diff))
if "y0" in obj:
new_items.append(("y0", obj["y0"] - diff))
return obj.__class__(tuple(obj.items()) + tuple(new_items))
def join_edge_group(edges, orientation: str, tolerance=DEFAULT_JOIN_TOLERANCE):
"""
Given a list of edges along the same infinite line, join those that
are within `tolerance` pixels of one another.
"""
if orientation == "h":
min_prop, max_prop = "x0", "x1"
elif orientation == "v":
min_prop, max_prop = "top", "bottom"
else:
raise ValueError("Orientation must be 'v' or 'h'")
sorted_edges = list(sorted(edges, key=itemgetter(min_prop)))
joined = [sorted_edges[0]]
for e in sorted_edges[1:]:
last = joined[-1]
if e[min_prop] <= (last[max_prop] + tolerance):
if e[max_prop] > last[max_prop]:
# Extend current edge to new extremity
joined[-1] = resize_object(last, max_prop, e[max_prop])
else:
# Edge is separate from previous edges
joined.append(e)
return joined
def merge_edges(
edges,
snap_x_tolerance,
snap_y_tolerance,
join_x_tolerance,
join_y_tolerance,
):
"""
Using the `snap_edges` and `join_edge_group` methods above,
merge a list of edges into a more "seamless" list.
"""
def get_group(edge):
if edge["orientation"] == "h":
return ("h", edge["top"])
else:
return ("v", edge["x0"])
if snap_x_tolerance > 0 or snap_y_tolerance > 0:
edges = snap_edges(edges, snap_x_tolerance, snap_y_tolerance)
_sorted = sorted(edges, key=get_group)
edge_groups = itertools.groupby(_sorted, key=get_group)
edge_gen = (
join_edge_group(
items, k[0], (join_x_tolerance if k[0] == "h" else join_y_tolerance)
)
for k, items in edge_groups
)
edges = list(itertools.chain(*edge_gen))
return edges
def bbox_to_rect(bbox) -> dict:
"""
Return the rectangle (i.e a dict with keys "x0", "top", "x1",
"bottom") for an object.
"""
return {"x0": bbox[0], "top": bbox[1], "x1": bbox[2], "bottom": bbox[3]}
def objects_to_rect(objects) -> dict:
"""
Given an iterable of objects, return the smallest rectangle (i.e. a
dict with "x0", "top", "x1", and "bottom" keys) that contains them
all.
"""
return bbox_to_rect(objects_to_bbox(objects))
def merge_bboxes(bboxes):
"""
Given an iterable of bounding boxes, return the smallest bounding box
that contains them all.
"""
x0, top, x1, bottom = zip(*bboxes)
return (min(x0), min(top), max(x1), max(bottom))
def objects_to_bbox(objects):
"""
Given an iterable of objects, return the smallest bounding box that
contains them all.
"""
return merge_bboxes(map(bbox_getter, objects))
def words_to_edges_h(words, word_threshold: int = DEFAULT_MIN_WORDS_HORIZONTAL):
"""
Find (imaginary) horizontal lines that connect the tops
of at least `word_threshold` words.
"""
by_top = cluster_objects(words, itemgetter("top"), 1)
large_clusters = filter(lambda x: len(x) >= word_threshold, by_top)
rects = list(map(objects_to_rect, large_clusters))
if len(rects) == 0:
return []
min_x0 = min(map(itemgetter("x0"), rects))
max_x1 = max(map(itemgetter("x1"), rects))
edges = []
for r in rects:
edges += [
# Top of text
{
"x0": min_x0,
"x1": max_x1,
"top": r["top"],
"bottom": r["top"],
"width": max_x1 - min_x0,
"orientation": "h",
},
# For each detected row, we also add the 'bottom' line. This will
# generate extra edges, (some will be redundant with the next row
# 'top' line), but this catches the last row of every table.
{
"x0": min_x0,
"x1": max_x1,
"top": r["bottom"],
"bottom": r["bottom"],
"width": max_x1 - min_x0,
"orientation": "h",
},
]
return edges
def get_bbox_overlap(a, b):
a_left, a_top, a_right, a_bottom = a
b_left, b_top, b_right, b_bottom = b
o_left = max(a_left, b_left)
o_right = min(a_right, b_right)
o_bottom = min(a_bottom, b_bottom)
o_top = max(a_top, b_top)
o_width = o_right - o_left
o_height = o_bottom - o_top
if o_height >= 0 and o_width >= 0 and o_height + o_width > 0:
return (o_left, o_top, o_right, o_bottom)
else:
return None
def words_to_edges_v(words, word_threshold: int = DEFAULT_MIN_WORDS_VERTICAL):
"""
Find (imaginary) vertical lines that connect the left, right, or
center of at least `word_threshold` words.
"""
# Find words that share the same left, right, or centerpoints
by_x0 = cluster_objects(words, itemgetter("x0"), 1)
by_x1 = cluster_objects(words, itemgetter("x1"), 1)
def get_center(word):
return float(word["x0"] + word["x1"]) / 2
by_center = cluster_objects(words, get_center, 1)
clusters = by_x0 + by_x1 + by_center
# Find the points that align with the most words
sorted_clusters = sorted(clusters, key=lambda x: -len(x))
large_clusters = filter(lambda x: len(x) >= word_threshold, sorted_clusters)
# For each of those points, find the bboxes fitting all matching words
bboxes = list(map(objects_to_bbox, large_clusters))
# Iterate through those bboxes, condensing overlapping bboxes
condensed_bboxes = []
for bbox in bboxes:
overlap = any(get_bbox_overlap(bbox, c) for c in condensed_bboxes)
if not overlap:
condensed_bboxes.append(bbox)
if len(condensed_bboxes) == 0:
return []
condensed_rects = map(bbox_to_rect, condensed_bboxes)
sorted_rects = list(sorted(condensed_rects, key=itemgetter("x0")))
max_x1 = max(map(itemgetter("x1"), sorted_rects))
min_top = min(map(itemgetter("top"), sorted_rects))
max_bottom = max(map(itemgetter("bottom"), sorted_rects))
return [
{
"x0": b["x0"],
"x1": b["x0"],
"top": min_top,
"bottom": max_bottom,
"height": max_bottom - min_top,
"orientation": "v",
}
for b in sorted_rects
] + [
{
"x0": max_x1,
"x1": max_x1,
"top": min_top,
"bottom": max_bottom,
"height": max_bottom - min_top,
"orientation": "v",
}
]
def edges_to_intersections(edges, x_tolerance=1, y_tolerance=1) -> dict:
"""
Given a list of edges, return the points at which they intersect
within `tolerance` pixels.
"""
intersections = {}
v_edges, h_edges = [
list(filter(lambda x: x["orientation"] == o, edges)) for o in ("v", "h")
]
for v in sorted(v_edges, key=itemgetter("x0", "top")):
for h in sorted(h_edges, key=itemgetter("top", "x0")):
if (
(v["top"] <= (h["top"] + y_tolerance))
and (v["bottom"] >= (h["top"] - y_tolerance))
and (v["x0"] >= (h["x0"] - x_tolerance))
and (v["x0"] <= (h["x1"] + x_tolerance))
):
vertex = (v["x0"], h["top"])
if vertex not in intersections:
intersections[vertex] = {"v": [], "h": []}
intersections[vertex]["v"].append(v)
intersections[vertex]["h"].append(h)
return intersections
def obj_to_bbox(obj):
"""
Return the bounding box for an object.
"""
return bbox_getter(obj)
def intersections_to_cells(intersections):
"""
Given a list of points (`intersections`), return all rectangular "cells"
that those points describe.
`intersections` should be a dictionary with (x0, top) tuples as keys,
and a list of edge objects as values. The edge objects should correspond
to the edges that touch the intersection.
"""
def edge_connects(p1, p2) -> bool:
def edges_to_set(edges):
return set(map(obj_to_bbox, edges))
if p1[0] == p2[0]:
common = edges_to_set(intersections[p1]["v"]).intersection(
edges_to_set(intersections[p2]["v"])
)
if len(common):
return True
if p1[1] == p2[1]:
common = edges_to_set(intersections[p1]["h"]).intersection(
edges_to_set(intersections[p2]["h"])
)
if len(common):
return True
return False
points = list(sorted(intersections.keys()))
n_points = len(points)
def find_smallest_cell(points, i: int):
if i == n_points - 1:
return None
pt = points[i]
rest = points[i + 1 :]
# Get all the points directly below and directly right
below = [x for x in rest if x[0] == pt[0]]
right = [x for x in rest if x[1] == pt[1]]
for below_pt in below:
if not edge_connects(pt, below_pt):
continue
for right_pt in right:
if not edge_connects(pt, right_pt):
continue
bottom_right = (right_pt[0], below_pt[1])
if (
(bottom_right in intersections)
and edge_connects(bottom_right, right_pt)
and edge_connects(bottom_right, below_pt)
):
return (pt[0], pt[1], bottom_right[0], bottom_right[1])
return None
cell_gen = (find_smallest_cell(points, i) for i in range(len(points)))
return list(filter(None, cell_gen))
def cells_to_tables(page, cells) -> list:
"""
Given a list of bounding boxes (`cells`), return a list of tables that
hold those cells most simply (and contiguously).
"""
def bbox_to_corners(bbox) -> tuple:
x0, top, x1, bottom = bbox
return ((x0, top), (x0, bottom), (x1, top), (x1, bottom))
remaining_cells = list(cells)
# Iterate through the cells found above, and assign them
# to contiguous tables
current_corners = set()
current_cells = []
tables = []
while len(remaining_cells):
initial_cell_count = len(current_cells)
for cell in list(remaining_cells):
cell_corners = bbox_to_corners(cell)
# If we're just starting a table ...
if len(current_cells) == 0:
# ... immediately assign it to the empty group
current_corners |= set(cell_corners)
current_cells.append(cell)
remaining_cells.remove(cell)
else:
# How many corners does this table share with the current group?
corner_count = sum(c in current_corners for c in cell_corners)
# If touching on at least one corner...
if corner_count > 0:
# ... assign it to the current group
current_corners |= set(cell_corners)
current_cells.append(cell)
remaining_cells.remove(cell)
# If this iteration did not find any more cells to append...
if len(current_cells) == initial_cell_count:
# ... start a new cell group
tables.append(list(current_cells))
current_corners.clear()
current_cells.clear()
# Once we have exhausting the list of cells ...
# ... and we have a cell group that has not been stored
if len(current_cells):
# ... store it.
tables.append(list(current_cells))
# PyMuPDF modification:
# Remove tables without text or having only 1 column
for i in range(len(tables) - 1, -1, -1):
r = EMPTY_RECT()
x1_vals = set()
x0_vals = set()
for c in tables[i]:
r |= c
x1_vals.add(c[2])
x0_vals.add(c[0])
if (
len(x1_vals) < 2
or len(x0_vals) < 2
or white_spaces.issuperset(
page.get_textbox(
r,
textpage=TEXTPAGE,
)
)
):
del tables[i]
# Sort the tables top-to-bottom-left-to-right based on the value of the
# topmost-and-then-leftmost coordinate of a table.
_sorted = sorted(tables, key=lambda t: min((c[1], c[0]) for c in t))
return _sorted
class CellGroup:
def __init__(self, cells):
self.cells = cells
self.bbox = (
min(map(itemgetter(0), filter(None, cells))),
min(map(itemgetter(1), filter(None, cells))),
max(map(itemgetter(2), filter(None, cells))),
max(map(itemgetter(3), filter(None, cells))),
)
class TableRow(CellGroup):
pass
class TableHeader:
"""PyMuPDF extension containing the identified table header."""
def __init__(self, bbox, cells, names, above):
self.bbox = bbox
self.cells = cells
self.names = names
self.external = above
class Table:
def __init__(self, page, cells):
self.page = page
self.cells = cells
self.header = self._get_header() # PyMuPDF extension
@property
def bbox(self):
c = self.cells
return (
min(map(itemgetter(0), c)),
min(map(itemgetter(1), c)),
max(map(itemgetter(2), c)),
max(map(itemgetter(3), c)),
)
@property
def rows(self) -> list:
_sorted = sorted(self.cells, key=itemgetter(1, 0))
xs = list(sorted(set(map(itemgetter(0), self.cells))))
rows = []
for y, row_cells in itertools.groupby(_sorted, itemgetter(1)):
xdict = {cell[0]: cell for cell in row_cells}
row = TableRow([xdict.get(x) for x in xs])
rows.append(row)
return rows
@property
def row_count(self) -> int: # PyMuPDF extension
return len(self.rows)
@property
def col_count(self) -> int: # PyMuPDF extension
return max([len(r.cells) for r in self.rows])
def extract(self, **kwargs) -> list:
chars = CHARS
table_arr = []
def char_in_bbox(char, bbox) -> bool:
v_mid = (char["top"] + char["bottom"]) / 2
h_mid = (char["x0"] + char["x1"]) / 2
x0, top, x1, bottom = bbox
return bool(
(h_mid >= x0) and (h_mid < x1) and (v_mid >= top) and (v_mid < bottom)
)
for row in self.rows:
arr = []
row_chars = [char for char in chars if char_in_bbox(char, row.bbox)]
for cell in row.cells:
if cell is None:
cell_text = None
else:
cell_chars = [
char for char in row_chars if char_in_bbox(char, cell)
]
if len(cell_chars):
kwargs["x_shift"] = cell[0]
kwargs["y_shift"] = cell[1]
if "layout" in kwargs:
kwargs["layout_width"] = cell[2] - cell[0]
kwargs["layout_height"] = cell[3] - cell[1]
cell_text = extract_text(cell_chars, **kwargs)
else:
cell_text = ""
arr.append(cell_text)
table_arr.append(arr)
return table_arr
def to_markdown(self, clean=True):
"""Output table content as a string in Github-markdown format.
If clean is true, markdown syntax is removed from cell content."""
output = "|"
# generate header string and MD underline
for i, name in enumerate(self.header.names):
if name is None or name == "": # generate a name if empty
name = f"Col{i+1}"
name = name.replace("\n", " ") # remove any line breaks
if clean: # remove sensitive syntax
name = html.escape(name.replace("-", "-"))
output += name + "|"
output += "\n"
output += "|" + "|".join("---" for i in range(self.col_count)) + "|\n"
# skip first row in details if header is part of the table
j = 0 if self.header.external else 1
# iterate over detail rows
for row in self.extract()[j:]:
line = "|"
for i, cell in enumerate(row):
# output None cells with empty string
cell = "" if cell is None else cell.replace("\n", " ")
if clean: # remove sensitive syntax
cell = html.escape(cell.replace("-", "-"))
line += cell + "|"
line += "\n"
output += line
return output + "\n"
def to_pandas(self, **kwargs):
"""Return a pandas DataFrame version of the table."""
try:
import pandas as pd
except ModuleNotFoundError:
message("Package 'pandas' is not installed")
raise
pd_dict = {}
extract = self.extract()
hdr = self.header
names = self.header.names
hdr_len = len(names)
# ensure uniqueness of column names
for i in range(hdr_len):
name = names[i]
if not name:
names[i] = f"Col{i}"
if hdr_len != len(set(names)):
for i in range(hdr_len):
name = names[i]
if name != f"Col{i}":
names[i] = f"{i}-{name}"
if not hdr.external: # header is part of 'extract'
extract = extract[1:]
for i in range(hdr_len):
key = names[i]
value = []
for j in range(len(extract)):
value.append(extract[j][i])
pd_dict[key] = value
return pd.DataFrame(pd_dict)
def _get_header(self, y_tolerance=3):
"""Identify the table header.
*** PyMuPDF extension. ***
Starting from the first line above the table upwards, check if it
qualifies to be part of the table header.
Criteria include:
* A one-line table never has an extra header.
* Column borders must not intersect any word. If this happens, all
text of this line and above of it is ignored.
* No excess inter-line distance: If a line further up has a distance
of more than 1.5 times of its font size, it will be ignored and
all lines above of it.
* Must have same text properties.
* Starting with the top table line, a bold text property cannot change
back to non-bold.
If not all criteria are met (or there is no text above the table),
the first table row is assumed to be the header.
"""
page = self.page
y_delta = y_tolerance
def top_row_is_bold(bbox):
"""Check if row 0 has bold text anywhere.
If this is true, then any non-bold text in lines above disqualify
these lines as header.
bbox is the (potentially repaired) row 0 bbox.
Returns True or False
"""
for b in page.get_text("dict", flags=TEXTFLAGS_TEXT, clip=bbox)["blocks"]:
for l in b["lines"]:
for s in l["spans"]:
if s["flags"] & 16:
return True
return False
try:
row = self.rows[0]
cells = row.cells
bbox = Rect(row.bbox)
except IndexError: # this table has no rows
return None
# return this if we determine that the top row is the header
header_top_row = TableHeader(bbox, cells, self.extract()[0], False)
# one-line tables have no extra header
if len(self.rows) < 2:
return header_top_row
# x-ccordinates of columns between x0 and x1 of the table
if len(cells) < 2:
return header_top_row
col_x = [
c[2] if c is not None else None for c in cells[:-1]
] # column (x) coordinates
# Special check: is top row bold?
# If first line above table is not bold, but top-left table cell is bold,
# we take first table row as header
top_row_bold = top_row_is_bold(bbox)
# clip = area above table
# We will inspect this area for text qualifying as column header.
clip = +bbox # take row 0 bbox
clip.y0 = 0 # start at top of page
clip.y1 = bbox.y0 # end at top of table
spans = [] # the text spans inside clip
for b in page.get_text("dict", clip=clip, flags=TEXTFLAGS_TEXT)["blocks"]:
for l in b["lines"]:
for s in l["spans"]:
if (
not s["flags"] & 1 and s["text"].strip()
): # ignore superscripts and empty text
spans.append(s)
select = [] # y1 coordinates above, sorted descending
line_heights = [] # line heights above, sorted descending
line_bolds = [] # bold indicator per line above, same sorting
# spans sorted descending
spans.sort(key=lambda s: s["bbox"][3], reverse=True)
# walk through the spans and fill above 3 lists
for i in range(len(spans)):
s = spans[i]
y1 = s["bbox"][3] # span bottom
h = y1 - s["bbox"][1] # span bbox height
bold = s["flags"] & 16
# use first item to start the lists
if i == 0:
select.append(y1)
line_heights.append(h)
line_bolds.append(bold)
continue
# get last items from the 3 lists
y0 = select[-1]
h0 = line_heights[-1]
bold0 = line_bolds[-1]
if bold0 and not bold:
break # stop if switching from bold to non-bold
# if fitting in height of previous span, modify bbox
if y0 - y1 <= y_delta or abs((y0 - h0) - s["bbox"][1]) <= y_delta:
s["bbox"] = (s["bbox"][0], y0 - h0, s["bbox"][2], y0)
spans[i] = s
if bold:
line_bolds[-1] = bold
continue
elif y0 - y1 > 1.5 * h0:
break # stop if distance to previous line too large
select.append(y1)
line_heights.append(h)
line_bolds.append(bold)
if select == []: # nothing above the table?
return header_top_row
select = select[:5] # only accept up to 5 lines in any header
# take top row as header if text above table is too far apart
if bbox.y0 - select[0] >= line_heights[0]:
return header_top_row
# if top table row is bold, but line above is not:
if top_row_bold and not line_bolds[0]:
return header_top_row
if spans == []: # nothing left above the table, return top row
return header_top_row
# re-compute clip above table
nclip = EMPTY_RECT()
for s in [s for s in spans if s["bbox"][3] >= select[-1]]:
nclip |= s["bbox"]
if not nclip.is_empty:
clip = nclip
clip.y1 = bbox.y0 # make sure we still include every word above
# Confirm that no word in clip is intersecting a column separator
word_rects = [Rect(w[:4]) for w in page.get_text("words", clip=clip)]
word_tops = sorted(list(set([r[1] for r in word_rects])), reverse=True)
select = []
# exclude lines with words that intersect a column border
for top in word_tops:
intersecting = [
(x, r)
for x in col_x
if x is not None
for r in word_rects
if r[1] == top and r[0] < x and r[2] > x
]
if intersecting == []:
select.append(top)
else: # detected a word crossing a column border
break
if select == []: # nothing left over: return first row
return header_top_row
hdr_bbox = +clip # compute the header cells
hdr_bbox.y0 = select[-1] # hdr_bbox top is smallest top coord of words
hdr_cells = [
(c[0], hdr_bbox.y0, c[2], hdr_bbox.y1) if c is not None else None
for c in cells
]
# adjust left/right of header bbox
hdr_bbox.x0 = self.bbox[0]
hdr_bbox.x1 = self.bbox[2]
# column names: no line breaks, no excess spaces
hdr_names = [
(
page.get_textbox(c).replace("\n", " ").replace(" ", " ").strip()
if c is not None
else ""
)
for c in hdr_cells
]
return TableHeader(tuple(hdr_bbox), hdr_cells, hdr_names, True)
@dataclass
class TableSettings:
vertical_strategy: str = "lines"
horizontal_strategy: str = "lines"
explicit_vertical_lines: list = None
explicit_horizontal_lines: list = None
snap_tolerance: float = DEFAULT_SNAP_TOLERANCE
snap_x_tolerance: float = UNSET
snap_y_tolerance: float = UNSET
join_tolerance: float = DEFAULT_JOIN_TOLERANCE
join_x_tolerance: float = UNSET
join_y_tolerance: float = UNSET
edge_min_length: float = 3
min_words_vertical: float = DEFAULT_MIN_WORDS_VERTICAL
min_words_horizontal: float = DEFAULT_MIN_WORDS_HORIZONTAL
intersection_tolerance: float = 3
intersection_x_tolerance: float = UNSET
intersection_y_tolerance: float = UNSET
text_settings: dict = None
def __post_init__(self) -> "TableSettings":
"""Clean up user-provided table settings.
Validates that the table settings provided consists of acceptable values and
returns a cleaned up version. The cleaned up version fills out the missing
values with the default values in the provided settings.
TODO: Can be further used to validate that the values are of the correct
type. For example, raising a value error when a non-boolean input is
provided for the key ``keep_blank_chars``.
:param table_settings: User-provided table settings.
:returns: A cleaned up version of the user-provided table settings.
:raises ValueError: When an unrecognised key is provided.
"""
for setting in NON_NEGATIVE_SETTINGS:
if (getattr(self, setting) or 0) < 0:
raise ValueError(f"Table setting '{setting}' cannot be negative")
for orientation in ["horizontal", "vertical"]:
strategy = getattr(self, orientation + "_strategy")
if strategy not in TABLE_STRATEGIES:
raise ValueError(
f"{orientation}_strategy must be one of"
f'{{{",".join(TABLE_STRATEGIES)}}}'
)
if self.text_settings is None:
self.text_settings = {}
# This next section is for backwards compatibility
for attr in ["x_tolerance", "y_tolerance"]:
if attr not in self.text_settings:
self.text_settings[attr] = self.text_settings.get("tolerance", 3)
if "tolerance" in self.text_settings:
del self.text_settings["tolerance"]
# End of that section
for attr, fallback in [
("snap_x_tolerance", "snap_tolerance"),
("snap_y_tolerance", "snap_tolerance"),
("join_x_tolerance", "join_tolerance"),
("join_y_tolerance", "join_tolerance"),
("intersection_x_tolerance", "intersection_tolerance"),
("intersection_y_tolerance", "intersection_tolerance"),
]:
if getattr(self, attr) is UNSET:
setattr(self, attr, getattr(self, fallback))
return self
@classmethod
def resolve(cls, settings=None):
if settings is None:
return cls()
elif isinstance(settings, cls):
return settings
elif isinstance(settings, dict):
core_settings = {}
text_settings = {}
for k, v in settings.items():
if k[:5] == "text_":
text_settings[k[5:]] = v
else:
core_settings[k] = v
core_settings["text_settings"] = text_settings
return cls(**core_settings)
else:
raise ValueError(f"Cannot resolve settings: {settings}")
class TableFinder:
"""
Given a PDF page, find plausible table structures.
Largely borrowed from Anssi Nurminen's master's thesis:
http://dspace.cc.tut.fi/dpub/bitstream/handle/123456789/21520/Nurminen.pdf?sequence=3
... and inspired by Tabula:
https://github.com/tabulapdf/tabula-extractor/issues/16
"""
def __init__(self, page, settings=None):
self.page = page
self.settings = TableSettings.resolve(settings)
self.edges = self.get_edges()
self.intersections = edges_to_intersections(
self.edges,
self.settings.intersection_x_tolerance,
self.settings.intersection_y_tolerance,
)
self.cells = intersections_to_cells(self.intersections)
self.tables = [
Table(self.page, cell_group)
for cell_group in cells_to_tables(self.page, self.cells)
]
def get_edges(self) -> list:
settings = self.settings
for orientation in ["vertical", "horizontal"]:
strategy = getattr(settings, orientation + "_strategy")
if strategy == "explicit":
lines = getattr(settings, "explicit_" + orientation + "_lines")
if len(lines) < 2:
raise ValueError(
f"If {orientation}_strategy == 'explicit', "
f"explicit_{orientation}_lines "
f"must be specified as a list/tuple of two or more "
f"floats/ints."
)
v_strat = settings.vertical_strategy
h_strat = settings.horizontal_strategy
if v_strat == "text" or h_strat == "text":
words = extract_words(CHARS, **(settings.text_settings or {}))
else:
words = []
v_explicit = []
for desc in settings.explicit_vertical_lines or []:
if isinstance(desc, dict):
for e in obj_to_edges(desc):
if e["orientation"] == "v":
v_explicit.append(e)
else:
v_explicit.append(
{
"x0": desc,
"x1": desc,
"top": self.page.rect[1],
"bottom": self.page.rect[3],
"height": self.page.rect[3] - self.page.rect[1],
"orientation": "v",
}
)
if v_strat == "lines":
v_base = filter_edges(EDGES, "v")
elif v_strat == "lines_strict":
v_base = filter_edges(EDGES, "v", edge_type="line")
elif v_strat == "text":
v_base = words_to_edges_v(words, word_threshold=settings.min_words_vertical)
elif v_strat == "explicit":
v_base = []
else:
v_base = []
v = v_base + v_explicit
h_explicit = []
for desc in settings.explicit_horizontal_lines or []:
if isinstance(desc, dict):
for e in obj_to_edges(desc):
if e["orientation"] == "h":
h_explicit.append(e)
else:
h_explicit.append(
{
"x0": self.page.rect[0],
"x1": self.page.rect[2],
"width": self.page.rect[2] - self.page.rect[0],
"top": desc,
"bottom": desc,
"orientation": "h",
}
)
if h_strat == "lines":
h_base = filter_edges(EDGES, "h")
elif h_strat == "lines_strict":
h_base = filter_edges(EDGES, "h", edge_type="line")
elif h_strat == "text":
h_base = words_to_edges_h(
words, word_threshold=settings.min_words_horizontal
)
elif h_strat == "explicit":
h_base = []
else:
h_base = []
h = h_base + h_explicit
edges = list(v) + list(h)
edges = merge_edges(
edges,
snap_x_tolerance=settings.snap_x_tolerance,
snap_y_tolerance=settings.snap_y_tolerance,
join_x_tolerance=settings.join_x_tolerance,
join_y_tolerance=settings.join_y_tolerance,
)
return filter_edges(edges, min_length=settings.edge_min_length)
def __getitem__(self, i):
tcount = len(self.tables)
if i >= tcount:
raise IndexError("table not on page")
while i < 0:
i += tcount
return self.tables[i]
"""
Start of PyMuPDF interface code.
The following functions are executed when "page.find_tables()" is called.
* make_chars: Fills the CHARS list with text character information extracted
via "rawdict" text extraction. Items in CHARS are formatted
as expected by the table code.
* make_edges: Fills the EDGES list with vector graphic information extracted
via "get_drawings". Items in EDGES are formatted as expected
by the table code.
The lists CHARS and EDGES are used to replace respective document access
of pdfplumber or, respectively pdfminer.
The table code has been modified to use these lists instead of accessing
page information themselves.
"""
# -----------------------------------------------------------------------------
# Extract all page characters to fill the CHARS list
# -----------------------------------------------------------------------------
def make_chars(page, clip=None):
"""Extract text as "rawdict" to fill CHARS."""
global CHARS, TEXTPAGE
page_number = page.number + 1
page_height = page.rect.height
ctm = page.transformation_matrix
TEXTPAGE = page.get_textpage(clip=clip, flags=TEXTFLAGS_TEXT)
blocks = page.get_text("rawdict", textpage=TEXTPAGE)["blocks"]
doctop_base = page_height * page.number
for block in blocks:
for line in block["lines"]:
ldir = line["dir"] # = (cosine, sine) of angle
ldir = (round(ldir[0], 4), round(ldir[1], 4))
matrix = Matrix(ldir[0], -ldir[1], ldir[1], ldir[0], 0, 0)
if ldir[1] == 0:
upright = True
else:
upright = False
for span in sorted(line["spans"], key=lambda s: s["bbox"][0]):
fontname = span["font"]
fontsize = span["size"]
color = sRGB_to_pdf(span["color"])
for char in sorted(span["chars"], key=lambda c: c["bbox"][0]):
bbox = Rect(char["bbox"])
bbox_ctm = bbox * ctm
origin = Point(char["origin"]) * ctm
matrix.e = origin.x
matrix.f = origin.y
text = char["c"]
char_dict = {
"adv": bbox.x1 - bbox.x0 if upright else bbox.y1 - bbox.y0,
"bottom": bbox.y1,
"doctop": bbox.y0 + doctop_base,
"fontname": fontname,
"height": bbox.y1 - bbox.y0,
"matrix": tuple(matrix),
"ncs": "DeviceRGB",
"non_stroking_color": color,
"non_stroking_pattern": None,
"object_type": "char",
"page_number": page_number,
"size": fontsize if upright else bbox.y1 - bbox.y0,
"stroking_color": color,
"stroking_pattern": None,
"text": text,
"top": bbox.y0,
"upright": upright,
"width": bbox.x1 - bbox.x0,
"x0": bbox.x0,
"x1": bbox.x1,
"y0": bbox_ctm.y0,
"y1": bbox_ctm.y1,
}
CHARS.append(char_dict)
# ------------------------------------------------------------------------
# Extract all page vector graphics to fill the EDGES list.
# We are ignoring Bézier curves completely and are converting everything
# else to lines.
# ------------------------------------------------------------------------
def make_edges(page, clip=None, tset=None, add_lines=None):
global EDGES
snap_x = tset.snap_x_tolerance
snap_y = tset.snap_y_tolerance
min_length = tset.edge_min_length
lines_strict = (
tset.vertical_strategy == "lines_strict"
or tset.horizontal_strategy == "lines_strict"
)
page_height = page.rect.height
doctop_basis = page.number * page_height
page_number = page.number + 1
prect = page.rect
if page.rotation in (90, 270):
w, h = prect.br
prect = Rect(0, 0, h, w)
if clip is not None:
clip = Rect(clip)
else:
clip = prect
def are_neighbors(r1, r2):
"""Detect whether r1, r2 are neighbors.
Defined as:
The minimum distance between points of r1 and points of r2 is not
larger than some delta.
This check supports empty rect-likes and thus also lines.
Note:
This type of check is MUCH faster than native Rect containment checks.
"""
if ( # check if x-coordinates of r1 are within those of r2
r2.x0 - snap_x <= r1.x0 <= r2.x1 + snap_x
or r2.x0 - snap_x <= r1.x1 <= r2.x1 + snap_x
) and ( # ... same for y-coordinates
r2.y0 - snap_y <= r1.y0 <= r2.y1 + snap_y
or r2.y0 - snap_y <= r1.y1 <= r2.y1 + snap_y
):
return True
# same check with r1 / r2 exchanging their roles (this is necessary!)
if (
r1.x0 - snap_x <= r2.x0 <= r1.x1 + snap_x
or r1.x0 - snap_x <= r2.x1 <= r1.x1 + snap_x
) and (
r1.y0 - snap_y <= r2.y0 <= r1.y1 + snap_y
or r1.y0 - snap_y <= r2.y1 <= r1.y1 + snap_y
):
return True
return False
def clean_graphics():
"""Detect and join rectangles of "connected" vector graphics."""
paths = [] # paths relevant for table detection
for p in page.get_drawings():
# ignore fill-only graphics if they do not simulate lines,
# which means one of width or height are small.
if (
p["type"] == "f"
and lines_strict
and p["rect"].width > snap_x
and p["rect"].height > snap_y
):
continue
paths.append(p)
# start with all vector graphics rectangles
prects = sorted(set([p["rect"] for p in paths]), key=lambda r: (r.y1, r.x0))
new_rects = [] # the final list of joined rectangles
# ----------------------------------------------------------------
# Strategy: Join rectangles that "almost touch" each other.
# Extend first rectangle with any other that is a "neighbor".
# Then move it to the final list and continue with the rest.
# ----------------------------------------------------------------
while prects: # the algorithm will empty this list
prect0 = prects[0] # copy of first rectangle (performance reasons!)
repeat = True
while repeat: # this loop extends first rect in list
repeat = False # set to true again if some other rect touches
for i in range(len(prects) - 1, 0, -1): # run backwards
if are_neighbors(prect0, prects[i]): # close enough to rect 0?
prect0 |= prects[i].tl # extend rect 0
prect0 |= prects[i].br # extend rect 0
del prects[i] # delete this rect
repeat = True # keep checking the rest
# move rect 0 over to result list if there is some text in it
if not white_spaces.issuperset(page.get_textbox(prect0, textpage=TEXTPAGE)):
# contains text, so accept it as a table bbox candidate
new_rects.append(prect0)
del prects[0] # remove from rect list
return new_rects, paths
bboxes, paths = clean_graphics()
def is_parallel(p1, p2):
"""Check if line is roughly axis-parallel."""
if abs(p1.x - p2.x) <= snap_x or abs(p1.y - p2.y) <= snap_y:
return True
return False
def make_line(p, p1, p2, clip):
"""Given 2 points, make a line dictionary for table detection."""
if not is_parallel(p1, p2): # only accepting axis-parallel lines
return {}
# compute the extremal values
x0 = min(p1.x, p2.x)
x1 = max(p1.x, p2.x)
y0 = min(p1.y, p2.y)
y1 = max(p1.y, p2.y)
# check for outside clip
if x0 > clip.x1 or x1 < clip.x0 or y0 > clip.y1 or y1 < clip.y0:
return {}
if x0 < clip.x0:
x0 = clip.x0 # adjust to clip boundary
if x1 > clip.x1:
x1 = clip.x1 # adjust to clip boundary
if y0 < clip.y0:
y0 = clip.y0 # adjust to clip boundary
if y1 > clip.y1:
y1 = clip.y1 # adjust to clip boundary
width = x1 - x0 # from adjusted values
height = y1 - y0 # from adjusted values
if width == height == 0:
return {} # nothing left to deal with
line_dict = {
"x0": x0,
"y0": page_height - y0,
"x1": x1,
"y1": page_height - y1,
"width": width,
"height": height,
"pts": [(x0, y0), (x1, y1)],
"linewidth": p["width"],
"stroke": True,
"fill": False,
"evenodd": False,
"stroking_color": p["color"] if p["color"] else p["fill"],
"non_stroking_color": None,
"object_type": "line",
"page_number": page_number,
"stroking_pattern": None,
"non_stroking_pattern": None,
"top": y0,
"bottom": y1,
"doctop": y0 + doctop_basis,
}
return line_dict
for p in paths:
items = p["items"] # items in this path
# if 'closePath', add a line from last to first point
if p["closePath"] and items[0][0] == "l" and items[-1][0] == "l":
items.append(("l", items[-1][2], items[0][1]))
for i in items:
if i[0] not in ("l", "re", "qu"):
continue # ignore anything else
if i[0] == "l": # a line
p1, p2 = i[1:]
line_dict = make_line(p, p1, p2, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
elif i[0] == "re":
# A rectangle: decompose into 4 lines, but filter out
# the ones that simulate a line
rect = i[1].normalize() # normalize the rectangle
if (
rect.width <= min_length and rect.width < rect.height
): # simulates a vertical line
x = abs(rect.x1 + rect.x0) / 2 # take middle value for x
p1 = Point(x, rect.y0)
p2 = Point(x, rect.y1)
line_dict = make_line(p, p1, p2, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
continue
if (
rect.height <= min_length and rect.height < rect.width
): # simulates a horizontal line
y = abs(rect.y1 + rect.y0) / 2 # take middle value for y
p1 = Point(rect.x0, y)
p2 = Point(rect.x1, y)
line_dict = make_line(p, p1, p2, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
continue
line_dict = make_line(p, rect.tl, rect.bl, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
line_dict = make_line(p, rect.bl, rect.br, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
line_dict = make_line(p, rect.br, rect.tr, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
line_dict = make_line(p, rect.tr, rect.tl, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
else: # must be a quad
# we convert it into (up to) 4 lines
ul, ur, ll, lr = i[1]
line_dict = make_line(p, ul, ll, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
line_dict = make_line(p, ll, lr, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
line_dict = make_line(p, lr, ur, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
line_dict = make_line(p, ur, ul, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
path = {"color": (0, 0, 0), "fill": None, "width": 1}
for bbox in bboxes: # add the border lines for all enveloping bboxes
line_dict = make_line(path, bbox.tl, bbox.tr, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
line_dict = make_line(path, bbox.bl, bbox.br, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
line_dict = make_line(path, bbox.tl, bbox.bl, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
line_dict = make_line(path, bbox.tr, bbox.br, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
if add_lines is not None: # add user-specified lines
assert isinstance(add_lines, (tuple, list))
else:
add_lines = []
for p1, p2 in add_lines:
p1 = Point(p1)
p2 = Point(p2)
line_dict = make_line(path, p1, p2, clip)
if line_dict:
EDGES.append(line_to_edge(line_dict))
def page_rotation_set0(page):
"""Nullify page rotation.
To correctly detect tables, page rotation must be zero.
This function performs the necessary adjustments and returns information
for reverting this changes.
"""
mediabox = page.mediabox
rot = page.rotation # contains normalized rotation value
# need to derotate the page's content
mb = page.mediabox # current mediabox
if rot == 90:
# before derotation, shift content horizontally
mat0 = Matrix(1, 0, 0, 1, mb.y1 - mb.x1 - mb.x0 - mb.y0, 0)
elif rot == 270:
# before derotation, shift content vertically
mat0 = Matrix(1, 0, 0, 1, 0, mb.x1 - mb.y1 - mb.y0 - mb.x0)
else:
mat0 = Matrix(1, 0, 0, 1, -2 * mb.x0, -2 * mb.y0)
# prefix with derotation matrix
mat = mat0 * page.derotation_matrix
cmd = b"%g %g %g %g %g %g cm " % tuple(mat)
xref = TOOLS._insert_contents(page, cmd, 0)
# swap x- and y-coordinates
if rot in (90, 270):
x0, y0, x1, y1 = mb
mb.x0 = y0
mb.y0 = x0
mb.x1 = y1
mb.y1 = x1
page.set_mediabox(mb)
page.set_rotation(0)
# refresh the page to apply these changes
doc = page.parent
pno = page.number
page = doc[pno]
return page, xref, rot, mediabox
def page_rotation_reset(page, xref, rot, mediabox):
"""Reset page rotation to original values.
To be used before we return tables."""
doc = page.parent # document of the page
doc.update_stream(xref, b" ") # remove de-rotation matrix
page.set_mediabox(mediabox) # set mediabox to old value
page.set_rotation(rot) # set rotation to old value
pno = page.number
page = doc[pno] # update page info
return page
def find_tables(
page,
clip=None,
vertical_strategy: str = "lines",
horizontal_strategy: str = "lines",
vertical_lines: list = None,
horizontal_lines: list = None,
snap_tolerance: float = DEFAULT_SNAP_TOLERANCE,
snap_x_tolerance: float = None,
snap_y_tolerance: float = None,
join_tolerance: float = DEFAULT_JOIN_TOLERANCE,
join_x_tolerance: float = None,
join_y_tolerance: float = None,
edge_min_length: float = 3,
min_words_vertical: float = DEFAULT_MIN_WORDS_VERTICAL,
min_words_horizontal: float = DEFAULT_MIN_WORDS_HORIZONTAL,
intersection_tolerance: float = 3,
intersection_x_tolerance: float = None,
intersection_y_tolerance: float = None,
text_tolerance=3,
text_x_tolerance=3,
text_y_tolerance=3,
strategy=None, # offer abbreviation
add_lines=None, # optional user-specified lines
):
global CHARS, EDGES
CHARS = []
EDGES = []
old_small = bool(TOOLS.set_small_glyph_heights()) # save old value
TOOLS.set_small_glyph_heights(True) # we need minimum bboxes
if page.rotation != 0:
page, old_xref, old_rot, old_mediabox = page_rotation_set0(page)
else:
old_xref, old_rot, old_mediabox = None, None, None
if snap_x_tolerance is None:
snap_x_tolerance = UNSET
if snap_y_tolerance is None:
snap_y_tolerance = UNSET
if join_x_tolerance is None:
join_x_tolerance = UNSET
if join_y_tolerance is None:
join_y_tolerance = UNSET
if intersection_x_tolerance is None:
intersection_x_tolerance = UNSET
if intersection_y_tolerance is None:
intersection_y_tolerance = UNSET
if strategy is not None:
vertical_strategy = strategy
horizontal_strategy = strategy
settings = {
"vertical_strategy": vertical_strategy,
"horizontal_strategy": horizontal_strategy,
"explicit_vertical_lines": vertical_lines,
"explicit_horizontal_lines": horizontal_lines,
"snap_tolerance": snap_tolerance,
"snap_x_tolerance": snap_x_tolerance,
"snap_y_tolerance": snap_y_tolerance,
"join_tolerance": join_tolerance,
"join_x_tolerance": join_x_tolerance,
"join_y_tolerance": join_y_tolerance,
"edge_min_length": edge_min_length,
"min_words_vertical": min_words_vertical,
"min_words_horizontal": min_words_horizontal,
"intersection_tolerance": intersection_tolerance,
"intersection_x_tolerance": intersection_x_tolerance,
"intersection_y_tolerance": intersection_y_tolerance,
"text_tolerance": text_tolerance,
"text_x_tolerance": text_x_tolerance,
"text_y_tolerance": text_y_tolerance,
}
tset = TableSettings.resolve(settings=settings)
page.table_settings = tset
make_chars(page, clip=clip) # create character list of page
make_edges(
page, clip=clip, tset=tset, add_lines=add_lines
) # create lines and curves
tables = TableFinder(page, settings=tset)
TOOLS.set_small_glyph_heights(old_small)
if old_xref is not None:
page = page_rotation_reset(page, old_xref, old_rot, old_mediabox)
return tables
| 81,413 | Python | .py | 1,968 | 31.134146 | 89 | 0.556364 | pymupdf/PyMuPDF | 5,009 | 480 | 32 | AGPL-3.0 | 9/5/2024, 5:12:54 PM (Europe/Amsterdam) |