-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtoots.py
More file actions
148 lines (131 loc) · 5.26 KB
/
toots.py
File metadata and controls
148 lines (131 loc) · 5.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
from datetime import datetime
import logging
import json
import os
from flask import Blueprint, jsonify, Response, render_template, abort
from flask_cors import cross_origin
from .auth import login_exempt
from lib.mastodon_base import readTootsApiJson
from lib.Toot import Toot
from lib.TootForest import TootForest
from lib.shared import data_folder
bp = Blueprint('tweets', __name__, url_prefix='/tweets')
@bp.route('/')
@cross_origin()
@login_exempt
def root():
# Read the current tweets from the API or other source
current_tweets = readTootsApiJson()
# Read additional tweets from file_tweets_transformed.json
try:
with open(os.path.join(data_folder, 'file_tweets_transformed.json'), 'r', encoding='utf-8') as file:
file_tweets_data = json.load(file)
# Check if the data is a dictionary
if isinstance(file_tweets_data, dict):
# If the current tweets are also a dictionary, update it
if isinstance(current_tweets, dict):
current_tweets.update(file_tweets_data)
# If the current tweets are a list, convert the dictionary to a list and extend it
elif isinstance(current_tweets, list):
current_tweets.extend(file_tweets_data.values())
else:
raise ValueError("The current tweets are neither a list nor a dictionary.")
else:
raise ValueError("The contents of file_tweets_transformed.json are not a dictionary")
except FileNotFoundError:
logging.error("The file file_tweets_transformed.json was not found.")
except json.JSONDecodeError:
logging.error("The file file_tweets_transformed.json does not contain valid JSON.")
except ValueError as e:
logging.error(e)
# Return the combined data as a JSON response
return Response(json.dumps({
'date': int(datetime.timestamp(datetime.now())),
'tweets': current_tweets
}), mimetype='application/json')
@bp.route('/<int:id>')
def tweet(id):
tweet = Toot.loadFromFile(id)
return jsonify(tweet.data)
@bp.route('/forest')
def forest_show():
return render_template('forest.html.j2', forest = TootForest.fromFolder())
#return Response(str(forest), mimetype='text/plain')
@bp.route('/forest/renew')
def forest_create():
logging.warning('Manual invocation of creating forest!')
forest = TootForest.fromFolder()
forest.saveApiJson()
# Read the current tweets from the API or other source
current_tweets = readTootsApiJson()
# Read additional tweets from file_tweets_transformed.json
try:
with open(os.path.join(data_folder, 'file_tweets_transformed.json'), 'r', encoding='utf-8') as file:
file_tweets_data = json.load(file)
# Check if the data is a dictionary
if isinstance(file_tweets_data, dict):
# If the current tweets are also a dictionary, update it
if isinstance(current_tweets, dict):
current_tweets.update(file_tweets_data)
# If the current tweets are a list, convert the dictionary to a list and extend it
elif isinstance(current_tweets, list):
current_tweets.extend(file_tweets_data.values())
else:
raise ValueError("The current tweets are neither a list nor a dictionary.")
else:
raise ValueError("The contents of file_tweets_transformed.json are not a dictionary")
except FileNotFoundError:
logging.error("The file file_tweets_transformed.json was not found.")
except json.JSONDecodeError:
logging.error("The file file_tweets_transformed.json does not contain valid JSON.")
except ValueError as e:
logging.error(e)
# Return the combined data as a JSON response
return Response(json.dumps(current_tweets), mimetype='application/json')
@bp.route('/add/<int:id>')
def add(id):
logging.warning('Manual invocation of adding tweet (id: {})!'.format(id))
tweet = Toot.loadFromMastodon(id)
tweet.save()
# renew forest
forest = TootForest.fromFolder()
forest.saveApiJson()
return jsonify({
'message': 'added',
'tweet': {
'id': id,
'data': tweet.data
}
})
@bp.route('/delete/<int:id>')
def delete(id):
logging.warning('Manual invocation of deleting tweet (id: {})!'.format(id))
tweet = Toot.loadFromFile(id)
tweet.delete()
# renew forest
forest = TootForest.fromFolder()
forest.saveApiJson()
return jsonify({
'message': 'deleted',
'tweet': {
'id': id,
'data': tweet.data
}
})
@bp.route('/all')
def all():
tweets = Toot.loadFromFolder()
tweets.sort(key = lambda x: x.getDateTime(), reverse = True)
# [Toot(i) for i in tweets]
return render_template('all.html.j2', tweets = tweets)
@bp.route('/stories')
def info():
tweets = readTootsApiJson()
stories = {};
for id, info in tweets.items():
if 'story' in info:
storyId = info['story']
if storyId not in stories:
stories[storyId] = []
stories[storyId].append(Toot.loadFromFile(id))
return render_template('stories.html.j2', stories = stories)