hyperfocus/main.go

455 lines
11 KiB
Go
Raw Normal View History

2021-10-26 18:13:24 +02:00
package main
import (
"bufio"
2021-12-30 02:17:59 +01:00
"context"
2021-12-24 05:12:05 +01:00
"errors"
2021-10-26 18:13:24 +02:00
"fmt"
"io"
2021-10-26 18:13:24 +02:00
"log"
"os"
"os/signal"
"os/user"
2021-12-30 02:17:59 +01:00
"path/filepath"
2021-10-26 18:13:24 +02:00
"runtime"
"time"
"github.com/akamensky/argparse"
)
2022-01-04 17:42:59 +01:00
var localFilePaths = make(map[string]string, 4)
// Check if <path> exists on the host filesystem
2021-12-24 05:12:05 +01:00
func fileExists(path string) bool {
_, err := os.Stat(path)
return !errors.Is(err, os.ErrNotExist)
}
2022-01-04 17:42:59 +01:00
func getLocalFilePaths() {
switch runtime.GOOS {
case "windows":
localFilePaths["hosts"] = filepath.Clean("C:\\Windows\\System32\\drivers\\etc\\hosts")
localFilePaths["hostsBackup"] = filepath.Clean("C:\\Windows\\System32\\drivers\\etc\\hosts.backup")
localFilePaths["uDistractors"] = filepath.Clean(os.Getenv("HOME") + "\\.hf_distractors")
localFilePaths["pDistractors"] = filepath.Clean(os.Getenv("HOME") + "\\.hf_predef_distractors")
default:
localFilePaths["hosts"] = filepath.Clean("/etc/hosts")
localFilePaths["hostsBackup"] = filepath.Clean("/etc/.hosts.backup")
localFilePaths["uDistractors"] = filepath.Clean("/etc/hf_distractors")
localFilePaths["pDistractors"] = filepath.Clean("/etc/hf_predef_distractors")
}
}
// Copy src to dest
func copyFile(src string, dest string) error {
2022-01-04 17:42:59 +01:00
origFile, err := os.Open(src)
if err != nil {
return fmt.Errorf("could not open original file %s for copying: %s", src, err)
}
2022-01-04 17:42:59 +01:00
backupFile, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return fmt.Errorf("could not open backup file %s for writing: %s", dest, err)
}
_, err = io.Copy(backupFile, origFile)
if err != nil {
return fmt.Errorf("could not copy %s to %s: %s", src, dest, err)
}
return nil
}
2022-01-04 17:42:59 +01:00
// Check if running as super user
func isRoot() bool {
2021-10-26 18:13:24 +02:00
2022-01-04 17:42:59 +01:00
var isSu bool
switch runtime.GOOS {
2021-10-26 18:13:24 +02:00
case "windows":
2022-01-04 17:42:59 +01:00
_, err := os.Open("\\\\.\\PHYSICALDRIVE0")
if err != nil {
isSu = false
} else {
isSu = true
}
2021-10-26 18:13:24 +02:00
default:
2022-01-04 17:42:59 +01:00
currUser, err := user.Current()
if err != nil {
log.Fatalf("[Super user check] Unable to get current user: %s\n", err)
}
isSu = currUser.Username == "root"
2021-10-26 18:13:24 +02:00
}
2022-01-04 17:42:59 +01:00
return isSu
2021-10-26 18:13:24 +02:00
}
// Disables access to websites that are defined as 'distractors'
func improveFocus() {
// Backup host file if a backup does not already exist
2022-01-04 17:42:59 +01:00
if !fileExists(localFilePaths["hostsBackup"]) {
if err := copyFile(localFilePaths["hosts"], localFilePaths["hostsBackup"]); err != nil {
log.Fatalln(err)
}
}
// Open host file for writing/appending
2022-01-04 17:42:59 +01:00
hostFileObj, err := os.OpenFile(localFilePaths["hosts"], os.O_APPEND|os.O_WRONLY, 0666)
2021-10-26 18:13:24 +02:00
if err != nil {
log.Fatalln(err)
}
2021-12-30 02:17:59 +01:00
defer func() {
2022-01-04 17:42:59 +01:00
if err := hostFileObj.Close(); err != nil {
2021-12-30 02:17:59 +01:00
log.Printf("Error closing file: %s\n", err)
}
}()
2021-10-26 18:13:24 +02:00
2021-12-30 03:57:15 +01:00
// For checking if /etc/hf_distractors or /etc/hf_distractors_predefined
// exist.
2021-12-24 05:12:05 +01:00
var (
distractorsFileWarn bool
predefDistractorsFileWarn bool
)
2021-12-30 02:17:59 +01:00
// If /etc/hf_distractors exists, take each host from it and append it
// to /etc/hosts for blocking. Else set distractorsFileWarn to true.
2022-01-04 17:42:59 +01:00
if fileExists(localFilePaths["uDistractors"]) {
2021-12-24 05:12:05 +01:00
2022-01-04 17:42:59 +01:00
distractorsFileObj, err := os.Open(localFilePaths["uDistractors"])
2021-12-24 05:12:05 +01:00
if err != nil {
log.Fatalln(err)
}
2021-12-30 02:17:59 +01:00
defer func() {
if err := distractorsFileObj.Close(); err != nil {
log.Printf("Error closing file: %s\n", err)
}
}()
2021-12-24 05:12:05 +01:00
scanner := bufio.NewScanner(distractorsFileObj)
for scanner.Scan() {
var hostLine string = fmt.Sprintf("127.0.0.1\t%s\n", scanner.Text())
2022-01-04 17:42:59 +01:00
if _, err := hostFileObj.WriteString(hostLine); err != nil {
2021-12-24 05:12:05 +01:00
log.Fatalln(err)
}
}
} else {
distractorsFileWarn = true
2021-10-26 18:13:24 +02:00
}
2021-12-30 02:17:59 +01:00
// If /etc/hf_predef_distractors exists, take each host from it and,
// append it to /etc/hosts for blocking. Else set predefDistractorsFileWarn to true.
2022-01-04 17:42:59 +01:00
if fileExists(localFilePaths["pDistractors"]) {
2021-12-24 05:12:05 +01:00
2022-01-04 17:42:59 +01:00
predefDistractorsFileObj, err := os.Open(localFilePaths["pDistractors"])
2021-12-24 05:12:05 +01:00
if err != nil {
2021-10-26 18:13:24 +02:00
log.Fatalln(err)
}
2021-12-30 02:17:59 +01:00
defer func() {
if err := predefDistractorsFileObj.Close(); err != nil {
log.Printf("Error closing file: %s\n", err)
}
}()
2021-12-24 05:12:05 +01:00
scanner := bufio.NewScanner(predefDistractorsFileObj)
for scanner.Scan() {
var hostLine string = fmt.Sprintf("127.0.0.1\t%s\n", scanner.Text())
2022-01-04 17:42:59 +01:00
if _, err := hostFileObj.WriteString(hostLine); err != nil {
2021-12-24 05:12:05 +01:00
log.Fatalln(err)
}
}
} else {
predefDistractorsFileWarn = true
}
// Fail with warning if neither distractors files exist.
2021-12-24 05:12:05 +01:00
if distractorsFileWarn && predefDistractorsFileWarn {
log.Fatalln("Error: Please define a set of distractors in your distractors file, one per line.",
"Alternatively, you can use a predefined set by running `sudo hf predefined`.")
2021-10-26 18:13:24 +02:00
}
2021-12-24 05:12:05 +01:00
fmt.Println("Focus is now improved 😊")
2021-10-26 18:13:24 +02:00
}
// Enables access to websites that are defined as 'distractors'
func loseFocus() {
// Remove the current /etc/hosts file before restoring the backup.
2022-01-04 17:42:59 +01:00
if err := os.Remove(localFilePaths["hosts"]); err != nil {
2021-10-26 18:13:24 +02:00
log.Fatalln(err)
}
// Restore the backup of /etc/hosts
2022-01-04 17:42:59 +01:00
if err := copyFile(localFilePaths["hostsBackup"], localFilePaths["hosts"]); err != nil {
2021-10-26 18:13:24 +02:00
log.Fatalln(err)
}
2021-12-24 05:12:05 +01:00
fmt.Println("Focus is now lost 🤪")
2021-10-26 18:13:24 +02:00
}
// Enables temporarily breaking concentration
func takeBreak(minutes int) {
fmt.Println()
fmt.Println("Your (probably) well-deserved break is commencing...")
loseFocus()
2021-12-30 03:57:15 +01:00
// Create notify context for os.Interrupt signal
2021-12-30 02:17:59 +01:00
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
2021-12-30 03:57:15 +01:00
// Create context with timeout for duration of minutes argument
2021-12-30 02:17:59 +01:00
ctx, cancel = context.WithTimeout(ctx, time.Duration(minutes*60)*time.Second)
defer cancel()
2021-12-30 02:17:59 +01:00
<-ctx.Done()
2021-10-26 18:13:24 +02:00
improveFocus()
}
// Prints the current list of distractors to be blocked
2021-12-30 03:57:15 +01:00
// If neither /etc/hf_distractors nor /etc/hf_predef_distractors exist,
2023-04-27 01:29:52 +02:00
// print error message to console and exit.
2021-10-26 18:13:24 +02:00
func listDistractors() {
2023-04-27 01:29:52 +02:00
if !fileExists(localFilePaths["uDistractors"]) && !fileExists(localFilePaths["pDistractors"]) {
fmt.Printf("%s not found\n", localFilePaths["uDistractors"])
fmt.Printf("%s not found\n", localFilePaths["pDistractors"])
os.Exit(1)
2021-12-30 02:17:59 +01:00
}
2023-04-27 01:29:52 +02:00
if fileExists(localFilePaths["uDistractors"]) {
// Open /etc/hf_distractors and store it as *os.File type
userDistractorsFileObj, err := os.Open(localFilePaths["uDistractors"])
if err != nil {
fmt.Println(err)
}
2023-04-27 01:29:52 +02:00
defer func() {
if err := userDistractorsFileObj.Close(); err != nil {
fmt.Printf("Error closing file: %s\n", err)
}
}()
2021-10-26 18:13:24 +02:00
2023-04-27 01:29:52 +02:00
// Initialize a new scanner, scan /etc/hf_distractors, and print to
// stdout line by line.
scanner := bufio.NewScanner(userDistractorsFileObj)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
2021-12-30 02:17:59 +01:00
}
2023-04-27 01:29:52 +02:00
if fileExists(localFilePaths["pDistractors"]) {
// Open /etc/hf_predef_distractors and store it as *os.File type
predefDistractorsFileObj, err := os.Open(localFilePaths["pDistractors"])
if err != nil {
fmt.Println(err)
}
2023-04-27 01:29:52 +02:00
defer func() {
if err := predefDistractorsFileObj.Close(); err != nil {
fmt.Printf("Error closing file: %s\n", err)
}
}()
2021-12-30 02:17:59 +01:00
2023-04-27 01:29:52 +02:00
// Initialize a new scanner, scan /etc/hf_predef_distractors, and print to
// stdout line by line.
scanner := bufio.NewScanner(predefDistractorsFileObj)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
2021-10-26 18:13:24 +02:00
}
}
2021-12-30 03:57:15 +01:00
// Adds predefined distractors to /etc/hf_predef_distractors file
2021-10-26 18:13:24 +02:00
func addPredefinedDistractors() {
2021-12-30 03:57:15 +01:00
// Slice of distractor domains
distractors := []string{
2021-12-24 05:12:05 +01:00
"anandtech.com",
"answerbag.com",
"arstechnica.com",
"awkwardfamilyphotos.com",
"bbc.com",
"befunky.com",
"break.com",
"buzzfeed.com",
"cheezburger.com",
"cnet.com",
"cnn.com",
"cracked.com",
"digg.com",
"digitaltrends.com",
"distrowatch.com",
"ebay.com",
"engadget.com",
"everypoet.com",
"facebook.com",
2021-12-24 05:12:05 +01:00
"failblog.com",
"fark.com",
"firstpost.com",
"flyertalk.com",
"fmylife.com",
"fox.com",
"freerice.com",
"gawker.com",
2021-12-24 05:12:05 +01:00
"geek.com",
"gizmag.com",
"gizmodo.com",
2021-12-24 05:12:05 +01:00
"gsmarena.com ",
"homestarrunner.com",
"hulu.com",
"imgur.com",
2021-12-24 05:12:05 +01:00
"imore.com",
"instagram.com",
2021-12-24 05:12:05 +01:00
"iwastesomuchtime.com",
"lifehacker.com",
"liveplasma.com",
"lunchtimers.com",
"mashable.com",
"mcsweeneys.net",
"medium.com",
"meetup.com",
2021-12-24 05:12:05 +01:00
"mono-1.com",
"myparentsjoinedfacebook.com",
"myspace.com",
"netflix.com",
"news.anandtech.com",
"news.arstechnica.com",
"news.buzzfeed.com",
"news.cheezburger.com",
"news.cnet.com",
"news.cracked.com",
"news.distrowatch.com",
"news.ebay.com",
"news.facebook.com",
"news.gizmodo.com",
"news.homestarrunner.com",
"news.imgur.com",
"news.lifehacker.com",
"news.meetup.com",
"news.myspace.com",
"news.reddit.com",
"news.sciencemag.org",
"news.slashdot.com",
"news.slashdot.org",
"news.stripgenerator.com",
"news.theverge.com",
"news.trulia.com",
"news.typepad.com",
"news.ycombinator.com",
"news.ycombinator.com",
"news.yelp.com",
"news.youtube.com",
2021-12-24 05:12:05 +01:00
"notalwaysright.com",
"omegle.com",
"opentable.com",
2021-12-24 05:12:05 +01:00
"passiveaggressivenotes.com",
"pcworld.com",
2021-12-24 05:12:05 +01:00
"petsinclothes.com",
"phoronix.com",
"pinterest.com",
"pogo.com",
"popurls.com",
"postsecret.com",
2021-12-24 05:12:05 +01:00
"realclearpolitics.com",
"realtor.com",
"reddit.com",
"redfin.com",
"sciencemag.org",
"sho.com",
"slashdot.com",
"slashdot.org",
"slickdeals.net",
"stripgenerator.com",
"techcrunch.com",
"technorati.com",
"techradar.com",
"techrepublic.com",
"textsfromlastnight.com",
2021-12-24 05:12:05 +01:00
"thenextweb.com",
"thepointsguy.com",
"theverge.com",
"tomshardware.com",
"trulia.com",
"tumblr.com",
"twitter.com",
"twitterfall.com",
2021-12-24 05:12:05 +01:00
"typepad.com",
"wearables.com",
"wired.com",
"woot.com",
"xkcd.com",
"yelp.com",
"youtube.com",
"zdnet.com",
"zillow.com",
}
2021-12-30 03:57:15 +01:00
// Open or create /etc/hf_predef_distractors and store it in *os.File type
2022-01-04 17:42:59 +01:00
fmt.Println(localFilePaths["pDistractors"])
predefDistractorsFileObj, err := os.OpenFile(localFilePaths["pDistractors"], os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatalln(err)
}
2021-12-30 02:17:59 +01:00
defer func() {
if err := predefDistractorsFileObj.Close(); err != nil {
log.Printf("Error closing file: %s\n", err)
}
}()
2021-12-30 03:57:15 +01:00
// Initialize a new writer, range loop over distractors slice, and write
// each distractor domain to /etc/hf_predef_distractors, line by line.
2021-12-24 05:12:05 +01:00
dataWriter := bufio.NewWriter(predefDistractorsFileObj)
for _, v := range distractors {
2021-12-24 05:12:05 +01:00
_, _ = dataWriter.WriteString(v + "\n")
}
2021-12-30 02:17:59 +01:00
if err := dataWriter.Flush(); err != nil {
log.Fatalln(err)
}
2021-10-26 18:13:24 +02:00
}
func main() {
2021-12-30 03:57:15 +01:00
parser := argparse.NewParser("go-hyperfocus", "Block distracting websites and hyperfocus on your work")
2021-10-26 18:13:24 +02:00
improveCmd := parser.NewCommand("improve", "Improve focus, block the distractors")
loseCmd := parser.NewCommand("lose", "Lose focus, unblock the distractors")
breakCmd := parser.NewCommand("break", "Take a break for a number of minutes")
minutesForBreak := breakCmd.Int("", "minutes", &argparse.Options{Help: "Number of minutes to break for."})
2021-12-30 03:57:15 +01:00
listCmd := parser.NewCommand("list", "List the distractors defined in the block file (/etc/hf_distractors)")
predefinedCmd := parser.NewCommand("predefined", "Add predefined set of distractors to /etc/hf_predef_distractors")
2021-10-26 18:13:24 +02:00
if isRoot() {
2022-01-04 17:42:59 +01:00
getLocalFilePaths()
err := parser.Parse(os.Args)
if err != nil {
fmt.Print(parser.Usage(err))
}
if improveCmd.Happened() {
improveFocus()
} else if loseCmd.Happened() {
loseFocus()
} else if breakCmd.Happened() {
takeBreak(*minutesForBreak)
} else if listCmd.Happened() {
listDistractors()
} else if predefinedCmd.Happened() {
addPredefinedDistractors()
} else {
fmt.Println("Enter a subcommand; use --help or -h for details.")
}
2021-10-26 18:13:24 +02:00
} else {
fmt.Println("Super user not detected. This program requires root privileges; please re-run with sudo or become root.")
2021-10-26 18:13:24 +02:00
}
}