This repository has been archived by the owner on Jan 14, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathdeleter.go
executable file
·431 lines (378 loc) · 11.6 KB
/
deleter.go
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//usr/bin/env go run $0 "$@"; exit
package main
import (
"fmt"
"github.com/AlecAivazis/survey"
"github.com/cheggaaa/pb/v3"
"github.com/juju/persistent-cookiejar"
"io/ioutil"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const numRoutines int = 5
const facebookURL string = "https://mbasic.facebook.com"
const facebookLoginURL string = "https://mbasic.facebook.com/login/device-based/regular/login/"
const profileURL string = "https://mbasic.facebook.com/profile"
const activityURL string = "https://mbasic.facebook.com/<profileid>/allactivity"
const anyMonthString string = "Any month"
var yearOptions = []string{"2020", "2019", "2018", "2017", "2016", "2015", "2014", "2013", "2012", "2011", "2010", "2009", "2008", "2007", "2006"}
var monthStrings = []string{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}
var categoriesMap = map[string]string{
"Comments": "commentscluster",
"Posts": "statuscluster",
"Likes and Reactions": "likes",
"Search History": "search",
"Event Responses": "eventrsvps",
"Your Events": "createdevents",
"Event Invitations": "invitedevents",
"Photos and Videos": "photos",
"Group Posts, Comments, Reactions": "groupposts",
"Others' Posts To Your Timeline": "wallcluster",
"Posts You're Tagged In": "tagsbyotherscluster",
"All App Activity": "allapps",
"Instagram Photos and Videos": "genericapp&category_app_id=124024574287414",
"Spotify": "genericapp&category_app_id=174829003346",
}
var tokensInURLs = [...]string{"/removecontent", "/delete", "/report", "/events/remove.php", "&content_type=4&"}
type requester struct {
client *http.Client
jar *cookiejar.Jar
}
func newRequester() *requester {
req := new(requester)
req.jar, _ = cookiejar.New(&cookiejar.Options{})
req.client = &http.Client{Jar: req.jar}
return req
}
func (r *requester) Request(requestURL string) string {
requestURL = updateURL(requestURL)
resp, err := r.client.Get(requestURL)
return retrieveRequestString(resp, err)
}
func (r *requester) RequestPostForm(requestURL string, form url.Values) string {
requestURL = updateURL(requestURL)
resp, err := r.client.PostForm(requestURL, form)
return retrieveRequestString(resp, err)
}
func updateURL(requestURL string) string {
return strings.Replace(requestURL, "&", "&", -1)
}
func retrieveRequestString(resp *http.Response, err error) string {
if err != nil {
fmt.Println("error during http request")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("error during http request")
}
return string(body)
}
type fbLogin struct {
requester *requester
email string
password string
profileID string
}
func newFbLogin(req *requester) *fbLogin {
fbl := new(fbLogin)
fbl.requester = req
if !fbl.IsLoggedIn() {
fbl.EnterInformation()
fbl.Login()
req.jar.Save()
if !fbl.IsLoggedIn() {
panic("Failed to login")
}
}
return fbl
}
func (fbl *fbLogin) EnterInformation() {
email := ""
prompt := &survey.Input{
Message: "Please type your email",
}
survey.AskOne(prompt, &email)
password := ""
promptPW := &survey.Password{
Message: "Please type your password",
}
survey.AskOne(promptPW, &password)
fbl.email = email
fbl.password = password
}
func (fbl *fbLogin) Login() {
fmt.Println("Attempting Login...")
form := url.Values{
"email": {fbl.email},
"pass": {fbl.password},
"login": {"Log In"},
}
fbl.requester.RequestPostForm(facebookLoginURL, form)
}
func (fbl *fbLogin) IsLoggedIn() bool {
output := fbl.requester.Request(profileURL)
if strings.Contains(output, `name="sign_up"`) {
return false
}
fbl.StoreProfileID(output)
fbl.PrintUserName(output)
return true
}
func (fbl *fbLogin) StoreProfileID(output string) {
result := strings.Split(output, ";profile_id=")[1]
result = strings.Split(result, "&")[0]
fbl.profileID = result
}
func (fbl *fbLogin) PrintUserName(output string) {
result := strings.Split(output, `<title>`)[1]
result = strings.Split(result, `</title`)[0]
fmt.Println("Logged in with user:", result, "(profile ID:", fbl.profileID+")")
}
type deleteElement struct {
URL string
success bool
category string
token string
}
type activityReader struct {
req *requester
fbl *fbLogin
deleteElements []deleteElement
selectedMonths []string
}
func (actRead *activityReader) ReadItems(year int, month int, category string) {
requestURL, sectionIDStr := createRequestURL(year, month, actRead.fbl.profileID, category)
output := actRead.req.Request(requestURL)
moreCounter := 1
var searchString string
for {
actRead.StoreItemsFromOutput(output, category)
searchString = sectionIDStr + `_more_` + strconv.Itoa(moreCounter)
if !strings.Contains(output, searchString) {
break
}
actRead.UpdateOutputRead(month)
requestURL = strings.SplitAfter(output, searchString)[0]
requestURL = facebookURL + requestURL[strings.LastIndex(requestURL, `"`)+1:]
output = actRead.req.Request(requestURL)
moreCounter++
}
}
func (actRead *activityReader) StoreItemsFromOutput(out string, category string) {
for _, token := range tokensInURLs {
actRead.StoreItemsWithToken(out, token, category)
}
}
func getURLFromToString(htmlOut string, token string) (int, int) {
match := strings.Index(htmlOut, token)
if match == -1 {
return -1, -1
}
from := strings.LastIndex(htmlOut[:match], `"`) + 1
to := match + strings.Index(htmlOut[match:], `"`)
return from, to
}
func (actRead *activityReader) StoreItemsWithToken(out string, token string, category string) {
var from int
var to int
for {
from, to = getURLFromToString(out, token)
if from == -1 {
break
}
actRead.deleteElements = append(actRead.deleteElements, deleteElement{
facebookURL + out[from:to],
false, category, token})
out = out[to:]
}
}
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func (actRead *activityReader) UpdateOutputRead(month int) bool {
anyMonth := stringInSlice(anyMonthString, actRead.selectedMonths)
currentMonthSkip := true
str := "\r"
for i, monthString := range monthStrings {
if month > i {
if stringInSlice(monthString, actRead.selectedMonths) || anyMonth {
currentMonthSkip = false
str += monthString + " "
} else {
currentMonthSkip = true
str += "... "
}
} else {
str += " "
}
}
str += " Elements found:\t" + strconv.Itoa(len(actRead.deleteElements))
fmt.Printf(str)
return currentMonthSkip
}
func createRequestURL(year int, month int, profileID string, category string) (string, string) {
sectionIDStr := "sectionID=month_" + strconv.Itoa(year) + "_" + strconv.Itoa(month)
newURL := strings.Replace(activityURL, "<profileid>", profileID, 1)
newURL += "?category_key=" + categoriesMap[category]
newURL += "&timeend=" + toUnixTime(year, month+1, 1)
newURL += "×tart=" + toUnixTime(year, month, 0)
newURL += "&" + sectionIDStr
return newURL, sectionIDStr
}
func toUnixTime(year int, month int, decrement int64) string {
// Timezone should be PDT but `time.LoadLocation("America/Los_Angeles")` is not working as Windows executable
// see https://github.com/golang/go/issues/38453
timestamp := time.Date(year, time.Month(month), 1, 7, 0, 0, 0, time.UTC)
return strconv.FormatInt(timestamp.Unix()-decrement, 10)
}
func createMultiSelect(yearsOrCategories string, options []string) []string {
selected := []string{}
survey.MultiSelectQuestionTemplate = strings.Replace(survey.MultiSelectQuestionTemplate, "enter to select, type to filter", "space to select, enter to continue", 1)
prompt := &survey.MultiSelect{
Message: "Which " + yearsOrCategories,
Options: options,
PageSize: 20,
}
survey.AskOne(prompt, &selected)
return selected
}
func categorySlice() []string {
keys := []string{}
for key := range categoriesMap {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
type deleter struct {
actRead *activityReader
req *requester
}
func (del *deleter) Delete(years []string, categories []string) {
var wg sync.WaitGroup
for _, year := range years {
fmt.Println("Searching elements from " + year + ":")
yearInt, _ := strconv.Atoi(year)
for i := 1; i <= 12; i++ {
skip := del.actRead.UpdateOutputRead(i)
if skip {
continue
}
for _, category := range categories {
del.actRead.ReadItems(yearInt, i, category)
}
}
fmt.Println("\nDeleting elements from " + year + ":")
bar := pb.Full.Start(len(del.actRead.deleteElements))
wg.Add(numRoutines)
for i := 0; i < numRoutines; i++ {
go del.StartRoutine(i, bar, &wg)
}
wg.Wait()
bar.Finish()
del.actRead.deleteElements = make([]deleteElement, 0)
}
}
func (del *deleter) StartRoutine(ID int, bar *pb.ProgressBar, wg *sync.WaitGroup) {
var index int
l := len(del.actRead.deleteElements)
i := 0
for {
index = i*numRoutines + ID
if index >= l {
break
}
del.DeleteElement(&del.actRead.deleteElements[index])
bar.Increment()
i++
}
wg.Done()
}
func readDtsgTag(htmlOut string) string {
dtsgSearch := `name="fb_dtsg" value="`
match := strings.Index(htmlOut, dtsgSearch)
dtsgFrom := match + len(dtsgSearch)
dtsgEnd := strings.Index(htmlOut[dtsgFrom:], `"`)
return htmlOut[dtsgFrom : dtsgFrom+dtsgEnd]
}
func (del *deleter) Untag(elem *deleteElement) {
out := del.req.Request(elem.URL)
from, to := getURLFromToString(out, "/nfx/basic")
if from == -1 {
return
}
// Request "Yes, I'd like to continue filing this report."
out = del.req.Request(facebookURL + out[from:to])
from, to = getURLFromToString(out, "/nfx/basic")
if from == -1 {
return
}
out = del.req.RequestPostForm(facebookURL+out[from:to], url.Values{
"fb_dtsg": {readDtsgTag(out)},
"answer": {"spam"},
})
from, to = getURLFromToString(out, "/nfx/basic")
if from == -1 {
return
}
del.req.RequestPostForm(facebookURL+out[from:to], url.Values{
"fb_dtsg": {readDtsgTag(out)},
"action_key": {"UNTAG"},
"submit": {"Submit"},
})
elem.success = true
}
func (del *deleter) DeleteCoverOrProfilePhoto(elem *deleteElement) {
beginStr := "content_id="
beginIdx := strings.Index(elem.URL, beginStr) + len(beginStr)
endIdx := strings.Index(elem.URL, elem.token)
delURL := facebookURL + "/photo.php?fbid=" + elem.URL[beginIdx:endIdx] + "&delete&id=" + del.actRead.fbl.profileID
out := del.req.Request(delURL)
from, to := getURLFromToString(out, "/a/photo.php")
if from == -1 {
return
}
del.req.RequestPostForm(facebookURL+out[from:to], url.Values{
"fb_dtsg": {readDtsgTag(out)},
"confirm_photo_delete": {"1"},
"photo_delete": {"Delete"},
})
elem.success = true
}
func (del *deleter) DeleteElement(elem *deleteElement) {
if elem.token == "/report" {
// Removing tags in activity log has to request "Report",
// then select "It's spam", then "Remove tag"
del.Untag(elem)
} else if strings.Contains(elem.token, "content_type") {
if elem.category == "Photos and Videos" {
del.DeleteCoverOrProfilePhoto(elem)
}
} else {
del.req.Request(elem.URL)
elem.success = true
}
}
func main() {
req := newRequester()
fbl := newFbLogin(req)
actRead := activityReader{req, fbl, make([]deleteElement, 0), make([]string, 0)}
years := createMultiSelect("years", yearOptions)
monthSelect := append([]string{anyMonthString}, monthStrings...)
months := createMultiSelect("months", monthSelect)
actRead.selectedMonths = months
categories := createMultiSelect("categories", categorySlice())
del := deleter{&actRead, req}
del.Delete(years, categories)
}