xyzio

Convert magnet link to torrent file with Python and add additional trackers

leave a comment »

With rtorrent it is easier to have it pick up torrent files from a directory. This code converts a magnet link into a torrent file with Python and then inserts additional trackers to the torrent file.


import urllib
import HTMLParser

#This is the magnet link to modify
magnetLink = 'magnet:?xt=urn:btih:b54a3ba68fd398ed019e21290beecc9dda64a858&dn=wikipedia_en_all_novid_2018-06.zim&tr=udp%3a%2f%2ftracker.mg64.net'

#Here is a list of trackers to insert into the torrent
trackers = {'list','of','trackers'}

#Convert HTML special characters to escaped normal characters
magnetLink = urllib.unquote(magnetLink).decode('utf8')
magnetLink = HTMLParser.HTMLParser().unescape(magnetLink)

#Split out the trackers from the magnet link and save for later
magnetsplit = magnetLink.split('&tr=')
base = magnetsplit[0]
magnetTrackers = magnetsplit[1::]

#Add the trackers from the magnet link to our list of trackers
for magnetTracker in magnetTrackers:
    trackers.add(magnetTracker)

#Add the trackers
magnetLink = base
for tracker in trackers:
    magnetLink += '&tr=' + tracker

#Create the torrent file name - it is named after the magnet hash
magnetName = magnetLink[magnetLink.find("btih:") + 1:magnetLink.find("&")]
magnetName = magnetName.replace('tih:','')
torrentfilename = 'meta-' + magnetName + '.torrent'

#Write the magnet link to the torrent file
with open(torrentfilename, 'w') as o:
    linkstr = u'd10:magnet-uri' + str(len(magnetLink)) + u':' + magnetLink + u'e'
    linkstr = linkstr.encode('utf8')
    o.write(linkstr)


Written by M Kapoor

December 23, 2019 at 11:48 pm

Posted in Programming

Tagged with ,

Change Font Type in Clipboard with C#

leave a comment »

Convert text in the Clipboard to another font and re-save it to the clipboard in C#.


RichTextBox rtb = new RichTextBox();

//The new font is GenericMonospace
Font font = new Font(FontFamily.GenericMonospace, 10);

//Get text from the clipboard
rtb.Text = Clipboard.GetText();

//Select all text in the RichTextBox and apply fontstyle
rtb.SelectAll();
rtb.SelectionFont = font;

//Copy updated text back to the clipboard
rtb.Copy();

Written by M Kapoor

December 23, 2019 at 9:39 pm

Posted in Programming

Tagged with ,

Send an SMS from a Twilio sim via Programmable SMS

leave a comment »

Send an SMS from a Twilio sim via Programmable SMS to the outside world.

Enter this as TwiML in the SMS section of the ‘Progammable Voice and SMS’ in the settings menu for your sim.

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <!-- The from tag contains the phone number assigned to the sim -->
    <Message from="+19195551212" to="{{To}}">
     {{Body}} 
   </Message> 
</Response>

Written by M Kapoor

December 23, 2019 at 8:21 pm

Posted in Programming

Tagged with , , ,

Authenticate with BackBlaze B2 and list buckets with Python

with one comment

Authenticate with BackBlaze B2 and list buckets with Python.

First to authenticate with BackBlaze B2:


import requests
from requests.auth import HTTPBasicAuth

#Credentials from BackBlaze B2 manager
key_id          = 'b2_key_id'
application_key = 'b2_application_key'

#Contact authorization server and check response
path   = 'https://api.backblazeb2.com/b2api/v1/b2_authorize_account'
result = requests.get(path, auth=HTTPBasicAuth(key_id, application_key))
if result.status_code != 200:
    print 'Error - Could not connect to BackBlaze B2'
    exit()

#Get results and add authorization token to headers
result_json = result.json()
account_id  = result_json['accountId']
auth_token  = result_json['authorizationToken']
api_url     = result_json['apiUrl'] + '/b2api/v1'
api_session = requests.Session()
api_session.headers.update({ 'Authorization': auth_token })

Now use api_session to interact with B2. For example, download the list of buckets like this:


#Construct the API url
url = api_url + '/b2_list_buckets'

#Use the api_session parameter to get a list of buckets
bucketInfo = api_session.post(url, json={'accountId': account_id})

#Convert datastream to json
jsonBucketInfo = bucketInfo.json()

#List id and name
for bucket in jsonBucketInfo['buckets']:
    bucketId = bucket['bucketId']
    bucketName = bucket['bucketName']

    print bucketId, bucketName

More details about tokens in the json are on BackBlaze’s list_buckets API page.

Written by M Kapoor

December 23, 2019 at 8:05 pm

Posted in Programming

Tagged with ,

Authenticate with BackBlaze B2 and get file URLs using Python

leave a comment »

Authenticate with BackBlaze B2 and get the URLs of files in a bucket.

First to authenticate with BackBlaze B2:


import requests
from requests.auth import HTTPBasicAuth

#Auth information from Backblaze
key_id = 'key_id'
application_key = 'application_key'

#Authenticate
path = 'https://api.backblazeb2.com/b2api/v1/b2_authorize_account'
result = requests.get(path, auth=HTTPBasicAuth(key_id, application_key))
if result.status_code != 200:
    print 'Error - Could not connect to BackBlaze B2'
    exit()

#Read response
result_json = result.json()
account_id = result_json['accountId']
auth_token = result_json['authorizationToken']
api_url    = result_json['apiUrl'] + '/b2api/v1'
download_url = result_json['downloadUrl'] + '/file/'
api_session = requests.Session()
api_session.headers.update({ 'Authorization': auth_token })

Now get bucket contents and assemble URL. Sample code for bucket ID and bucket name is here.


#Initialize
bucketId = 'bucket_id_from_b2'
bucketName = 'name_of_bucket'

params = {'bucketId': bucketId}
urls = set()

#Loop for as long as a nextFile exists
while True:
    #Construct api call, execute, and read back information
    url = api_url + '/' + 'b2_list_file_names'
    fileList =  api_session.post(url, json=params)
    jFileList = fileList.json()

    #Loop through files and construct url
    for file in jFileList['files']:
        urls.add(download_url + bucketName + '/' + file['filename'])

    #Check for next file and break if it doesn't exist
    startFileName = jFileList['nextFileName']
    if startFileName == None:
        break
    else:
        #continue If next file exists
        params['startFileName'] = startFileName
        

Written by M Kapoor

December 23, 2019 at 7:17 pm

Posted in Programming

Tagged with ,

Forward SMS to multiple phone numbers with TwiML Bin

leave a comment »

Other parameters are possible like {{FromCity}} and {{FromState}}.  You can forward to multiple numbers by duplicating the Message tag.

More details here:
https://www.twilio.com/docs/sms/twiml

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Message to="+16623458765">Twilio: {{From}}: {{Body}}</Message>
    <Message to="+15033943032">Twilio: {{From}}: {{Body}}</Message>
</Response>

Written by M Kapoor

September 19, 2018 at 12:44 pm

Posted in twilio

Tagged with ,

Generate and save a static page in Django

leave a comment »

Generate and save a static page in Django.

Where
html/static.html is a Django template
data is the data you want to pass into the page
static(request) is a function mapped to a url in urls.py

Then
Visiting the page will generate this static file

Code

from django.template.loader import render_to_string

def static(request):
    results = render_to_string('html/static.html', {'content': html})
    with open(r'C:tempstatic.html','w') as f:
        f.write(results)

Written by M Kapoor

August 23, 2018 at 4:56 am