From 1fa9b9af1318f7301ef6b129820f44d577988e2a Mon Sep 17 00:00:00 2001 From: Zack Scholl Date: Tue, 9 Feb 2016 18:38:25 -0500 Subject: [PATCH] Versioning works with /edit Former-commit-id: 985172ae69b662d82d5ccdf43717293fe2ed15fb [formerly f0cd3a45bbdaf08230eeb33919389cb48190b367] [formerly 72cb8e73da135302b9cc81410934bfc569a2842d [formerly c15ac624b8e27598579fd64ee64e4f0251221760]] Former-commit-id: 50bcb25221501c8dcd2d02057e270c749bdcda4b [formerly 063bef228a2e193d7fe5d8879f02983bc68501c4] Former-commit-id: d004f2c61e3520bd284529ae6d64ffbb8f11a0c1 --- db.go | 22 +++-- main.go | 2 +- routes.go | 29 +++++-- templates/index.tmpl | 186 +++++++++++++++++++++++-------------------- utils.go | 51 +++++++++--- 5 files changed, 176 insertions(+), 114 deletions(-) diff --git a/db.go b/db.go index 4245057..aae6bb0 100644 --- a/db.go +++ b/db.go @@ -33,7 +33,7 @@ func Close() { db.Close() } -// Data for storing in DB +// CowyoData is data for storing in DB type CowyoData struct { Title string CurrentText string @@ -44,14 +44,14 @@ type CowyoData struct { func hasPassword(title string) (bool, error) { title = strings.ToLower(title) if !open { - return false, fmt.Errorf("db must be opened before loading!") + return false, fmt.Errorf("db must be opened before loading") } hasPassword := false err := db.View(func(tx *bolt.Tx) error { var err error b := tx.Bucket([]byte("datas")) if b == nil { - return fmt.Errorf("db must be opened before loading!") + return fmt.Errorf("db must be opened before loading") } k := []byte(title) val := b.Get(k) @@ -77,17 +77,19 @@ func hasPassword(title string) (bool, error) { return hasPassword, nil } -func getCurrentText(title string) string { +func getCurrentText(title string, version int) (string, []versionsInfo, bool) { title = strings.ToLower(title) + var vi []versionsInfo + isCurrent := true currentText := "" if !open { - return currentText + return currentText, vi, isCurrent } err := db.View(func(tx *bolt.Tx) error { var err error b := tx.Bucket([]byte("datas")) if b == nil { - return fmt.Errorf("db must be opened before loading!") + return fmt.Errorf("db must be opened before loading") } k := []byte(title) val := b.Get(k) @@ -100,12 +102,18 @@ func getCurrentText(title string) string { return err } currentText = p.CurrentText + if version > -1 && version < len(p.Diffs) { + // get that version of text instead + currentText = rebuildTextsToDiffN(p, version) + isCurrent = false + } + vi = getImportantVersions(p) return nil }) if err != nil { fmt.Printf("Could not get CowyoData: %s", err) } - return currentText + return currentText, vi, isCurrent } func (p *CowyoData) load(title string) error { diff --git a/main.go b/main.go index db39c7f..3b7332f 100644 --- a/main.go +++ b/main.go @@ -64,7 +64,7 @@ Options:`) var q CowyoData q.load("SpikySeaSlug2") - rebuildTexts(q) + fmt.Println(getImportantVersions(q)) r := gin.Default() r.LoadHTMLGlob(path.Join(RuntimeArgs.SourcePath, "templates/*")) diff --git a/routes.go b/routes.go index 8ff1e9d..7a5a9a0 100644 --- a/routes.go +++ b/routes.go @@ -34,14 +34,29 @@ func editNote(c *gin.Context) { if locked { c.Redirect(302, "/"+title+"/view") } else { - currentText := getCurrentText(title) + version := c.DefaultQuery("version", "-1") + versionNum, _ := strconv.Atoi(version) + currentText, versions, currentVersion := getCurrentText(title, versionNum) numRows := len(strings.Split(currentText, "\n")) + 10 - c.HTML(http.StatusOK, "index.tmpl", gin.H{ - "Title": title, - "ExternalIP": RuntimeArgs.ExternalIP, - "CurrentText": currentText, - "NumRows": numRows, - }) + if currentVersion { + c.HTML(http.StatusOK, "index.tmpl", gin.H{ + "Title": title, + "ExternalIP": RuntimeArgs.ExternalIP, + "CurrentText": currentText, + "NumRows": numRows, + "Versions": versions, + }) + } else { + c.HTML(http.StatusOK, "index.tmpl", gin.H{ + "Title": title, + "ExternalIP": RuntimeArgs.ExternalIP, + "CurrentText": currentText, + "NumRows": numRows, + "Versions": versions, + "NoEdit": true, + }) + } + } } } diff --git a/templates/index.tmpl b/templates/index.tmpl index 0916f81..15a4d8b 100644 --- a/templates/index.tmpl +++ b/templates/index.tmpl @@ -1,88 +1,98 @@ - - - - - {{ .Title }} - - {{ template "header" }} - - - - - - - - - - - - - - - - - - -
- -
- -
- -
- - - - - - + + + + + {{ .Title }} + + {{ template "header" }} + + + + + {{if .NoEdit}} {{else}} {{end}} + + + + + + + + + + + + + + +
+ +
+ +
+ +
+ + + + + + diff --git a/utils.go b/utils.go index ed02a0a..819395d 100644 --- a/utils.go +++ b/utils.go @@ -14,6 +14,11 @@ var animals []string var adjectives []string var robots_txt string +type versionsInfo struct { + VersionDate string + VersionNum int +} + func init() { rand.Seed(time.Now().Unix()) animals = []string{"fawn", "peacock", "fox terrier", "civet", "musk deer", "seastar", "pigeon", "bull", "bumblebee", "crocodile", "flying squirrel", "elephant", "leopard seal", "baboon", "porcupine", "wolverine", "spider monkey", "vampire bat", "sparrow", "manatee", "possum", "swallow", "wildcat", "bandicoot", "labradoodle", "dragonfly", "tarsier", "snowy owl", "chameleon", "boykin", "puffin", "bison", "llama", "kitten", "stinkbug", "macaw", "parrot", "leopard cat", "prawn", "panther", "dogfish", "fennec", "frigatebird", "nurse shark", "turkey", "cockatoo", "neanderthal", "crow", "gopher", "reindeer", "earwig ", "anaconda", "panda", "ant", "silver fox", "collared peccary", "puppy", "common buzzard", "moose", "binturong", "wildebeest", "lovebird", "ferret", "persian", "marine toad", "woolly mammoth", "dalmatian", "bird", "umbrellabird", "kingfisher", "kangaroo", "stallion", "russian blue", "ostrich", "owl", "tawny owl", "affenpinscher", "caiman", "elephant seal", "octopus", "meerkat", "whale shark", "buck", "donkey", "red wolf", "mountain lion", "labrador retriever", "quetzal", "chamois", "sponge", "hamster", "orangutan", "sea urchin", "uakari", "doberman", "dormouse", "saint bernard", "bull shark", "ocelot", "sparrow", "spitz", "stoat", "snapping turtle", "dragonfly", "cougar", "alligator", "walrus", "glass lizard", "malayan tiger", "frog", "tiger", "armadillo", "chinchilla", "crab", "squid", "calf", "shrew", "dolphin", "royal penguin", "dingo", "turtle", "yellow-eyed penguin", "chimpanzee", "armadillo", "boa constrictor", "rabbit", "basking", "coyote", "chinook", "osprey", "sea lion", "fly", "sperm whale", "patas monkey", "tiffany", "mountain goat", "dodo", "worm", "cat", "warthog", "peccary", "shark", "pony", "monkey", "swan", "whippet", "beagle", "cougar", "anteater", "quail", "liger", "cheetah", "woodpecker", "egret", "eagle", "moose", "warthog", "honey bee", "snail", "stag beetle", "budgie", "molly", "magpie", "rhinoceros", "elephant", "kudu", "wombat", "tree frog", "goat", "lamb", "tropicbird", "human", "hog", "tang", "pool frog", "lemur", "ox", "dog", "lizard", "echidna", "great dane", "wallaby", "hawk", "dove", "jellyfish", "sloth", "macaque", "starfish", "sun bear", "guppy", "welsh corgi", "deer", "impala", "porpoise", "gazelle", "bichon", "seal", "wolf", "zebra shark", "mole", "narwhal", "hedgehog", "sheep", "horse", "bluetick", "colt", "spadefoot toad", "wildebeest", "piranha", "basenji", "mallard", "bull mastiff", "bear", "siberian husky", "bird", "badger", "red panda", "hammerhead", "rock hyrax", "kangaroo", "marsh frog", "mule", "weasel", "dogfish", "dachsbracke", "forest elephant", "oyster", "bat", "python", "coati", "platypus", "salamander", "cat", "caterpillar", "giraffe", "snake", "kid", "falcon", "robin", "guinea fowl", "tern", "sea lion", "dingo", "bolognese", "drake", "goose", "rat", "gentoo penguin", "iguana", "quail", "mouse", "horseshoe crab", "roebuck", "cattle dog", "fish", "poodle", "frog", "wolverine", "chinchilla", "bobcat", "grey seal", "hermit crab", "carolina", "shepherd", "gila monster", "snail", "mandrill", "leopard", "frilled lizard", "echidna", "rabbit", "bison", "barracuda", "foal", "ass", "eagle", "octopus", "avocet", "siamese", "dodo", "yorkie", "cockroach", "wallaroo", "tiger", "woodlouse", "glow worm", "fossa", "buffalo", "zorse", "albatross", "indri", "seahorse", "lemur", "louse", "ostrich", "humpback whale", "millipede", "fin whale", "joey", "pinscher", "dachshund", "proboscis monkey", "pelican", "chihuahua", "dogo", "indian rhinoceros", "wasp", "siberian", "raccoon dog", "yak", "stingray", "jack russel", "water vole", "foxhound", "sheep", "stork", "horse", "monkey", "woolly monkey", "waterbuck", "dunker", "cuscus", "ibis", "giraffe", "aardvark", "hummingbird", "grizzly bear", "otter", "pike", "minke whale", "pika", "stickbug", "pelican", "dugong", "bongo", "lemming", "shrimp", "piglet", "sabre-toothed tiger", "gemsbok", "tiger shark", "tuatara", "rottweiler", "elephant shrew", "ewe", "coati", "cichlid", "akita", "gharial", "thorny devil", "duck", "macaroni penguin", "steer", "setter", "pufferfish", "donkey", "mink", "macaw", "wolfhound", "white tiger", "ram", "ant", "rat", "marten", "galapagos tortoise", "crab", "horn shark", "blue whale", "koala", "starfish", "partridge", "sea squirt", "fire-bellied toad", "chipmunk", "ibex", "maltese", "clumber", "butterfly", "manta ray", "flamingo", "opossum", "parrot", "mastiff", "water buffalo", "okapi", "salmon", "tapir", "adelie", "killer whale", "lynx", "basilisk", "indian elephant", "oyster", "manta ray", "prairie dog", "chipmunk", "locust", "dog", "cottontop", "hyena", "spectacled bear", "oriole", "cobra", "pug", "monitor", "mandrill", "antelope", "chinstrap", "zebra", "chicken", "mule", "seal", "goat", "little penguin", "gull", "tasmanian devil", "caterpillar", "tamarin", "wrasse", "woodchuck", "otter", "penguin", "porcupine", "killer whale", "bear", "ferret", "dusky", "nightingale", "slow worm", "bat", "jaguar", "humboldt", "ermine", "saola", "emu", "lobster", "weasel", "nightingale", "hound", "bombay", "platypus", "electric eel", "asian elephant", "sea otter", "uguisu", "scorpion", "fox", "jerboa", "bengal tiger", "zebu", "lion", "zonkey", "ragdoll", "caracal", "bee", "kiwi", "puma", "common loon", "jackal", "malamute", "mayfly", "baboon", "terrier", "jellyfish", "vicuna", "penguin", "desert tortoise", "muskrat", "water dragon", "zebra", "malayan civet", "burmese", "orangutan", "himalayan", "pond skater", "howler monkey", "newt", "border collie", "cow", "bearded dragon", "fish", "barn owl", "puffin", "chin", "anteater", "beaver", "canary", "hamster", "sloth", "collie", "heron", "sea dragon", "gopher", "magpie", "king crab", "flounder", "opossum", "pademelon", "capybara", "boar", "leaf-tailed gecko", "turkey", "clown fish", "musk-ox", "bulldog", "pronghorn", "hercules beetle", "reindeer", "llama", "pygmy", "eskimo dog", "kinkajou", "komodo dragon", "cuttlefish", "cub", "bloodhound", "squirrel", "gander", "moorhen", "emu", "brown bear", "javanese", "birman", "harrier", "tortoise", "antelope", "gnu", "kingfisher", "wasp", "olm", "havanese", "canaan", "lizard", "indochinese tiger", "ocelot", "mist", "hare", "discus", "cony", "orca", "rooster", "ground hog", "silver dollar", "peacock", "akbash", "somali", "beaver", "maine coon", "mouse", "eland", "squirrel", "serval", "chimpanzee", "snowshoe", "toucan", "catfish", "lynx", "coyote", "bunny", "retriever", "fur seal", "cow", "balinese", "vulture", "coral", "leopard", "raccoon", "polar bear", "okapi", "kakapo", "whale", "sand lizard", "bonobo", "moray", "gila monster", "cormorant", "bracke", "camel", "markhor", "rockhopper", "neapolitan", "black bear", "roseate spoonbill", "woodpecker", "mountain lion", "crested penguin", "hippopotamus", "puma", "camel", "alligator", "guinea pig", "heron", "siberian tiger", "river dolphin", "axolotl", "argentino", "human", "mongoose", "drever", "quokka", "common frog", "elk", "wombat", "spider monkey", "civet", "sting ray", "panther", "gar", "lionfish", "snake", "crane", "newt", "raven", "tortoise", "fire ant", "chicadee", "common toad", "pig", "manatee", "centipede", "numbat", "river turtle", "falcon", "angelfish", "chamois", "rhinoceros", "shark", "flamingo", "pheasant", "ladybird", "grasshopper", "greyhound", "lemming", "pig", "marmoset", "eel", "yorkiepoo", "tiger salamander", "mosquito", "shih tzu", "quoll", "chick", "guanaco", "walrus", "badger", "ainu", "squid", "pekingese", "gerbil", "duck", "rattlesnake", "tapir", "lobster", "catfish", "mustang", "wallaby", "mongrel", "butterfly", "booby", "bush elephant", "fox", "rattlesnake", "cockroach", "tadpole", "lark", "ape", "pied tamarin", "mare", "tetra", "squirrel monkey", "elephant seal", "dhole", "cesky", "raccoon", "newfoundland", "marmoset", "stag", "bullfrog", "black bear", "crocodile", "lion", "barb", "wolf", "vervet monkey", "beetle", "polar bear", "pointer", "grizzly bear", "meerkat", "owl", "reptile", "fousek", "gibbon", "king penguin", "budgerigar", "swan", "hartebeest", "cassowary", "borneo elephant", "oryx", "alpaca", "gerbil", "chameleon", "galapagos penguin", "vulture", "barracuda", "insect", "fishing cat", "hen", "giant clam", "hare", "polecat", "fly", "chow chow", "yak", "seahorse", "spider", "eel", "burro", "brown bear", "boxer dog", "crane", "bandicoot", "hedgehog", "dromedary", "goose", "budgerigar", "dolphin", "kelpie dog", "highland cattle", "dormouse", "duckbill", "springbok", "mongoose", "bobcat", "water buffalo", "gecko", "hornet", "iguana", "wild boar", "koala", "guinea pig", "marmot", "skink", "deer", "filly", "barnacle", "tree toad", "leopard tortoise", "appenzeller", "doe", "gecko", "mole", "mynah bird", "mau", "gilla monster", "french bulldog", "termite", "salamander", "parakeet", "finch", "horned frog", "hippopotamus", "hummingbird", "cheetah", "albatross", "jaguar", "toad", "hyena", "gorilla", "skunk", "impala", "sea slug", "scorpion fish", "jackal", "skunk", "grouse", "sea turtle", "moth", "caribou", "dugong", "bighorn sheep", "ibizan hound", "gorilla", "puffer fish", "chicken", "komodo dragon", "buffalo"} @@ -93,7 +98,7 @@ func diffRebuildtexts(diffs []diffmatchpatch.Diff) []string { return text } -func rebuildTexts(p CowyoData) { +func getImportantVersions(p CowyoData) []versionsInfo { m := map[int]int{} dmp := diffmatchpatch.New() lastText := "" @@ -104,14 +109,6 @@ func rebuildTexts(p CowyoData) { rebuilt := texts_linemode[len(texts_linemode)-1] parsedTime, _ := time.Parse(time.ANSIC, p.Timestamps[i]) duration := parsedTime.Sub(lastTime) - // fmt.Println(duration.Hours()) - // fmt.Println("---------------") - // fmt.Println(i, p.Timestamps[i]) - // fmt.Println(i, parsedTime) - // fmt.Println(i, lastTime) - // fmt.Println(i, duration) - // fmt.Println(i, rebuilt) - // fmt.Println("---------------") m[i] = int(duration.Seconds()) if i > 0 { m[i-1] = m[i] @@ -120,7 +117,8 @@ func rebuildTexts(p CowyoData) { lastText = rebuilt lastTime = parsedTime } - fmt.Println(m) + + // Sort in order of decreasing diff times n := map[int][]int{} var a []int for k, v := range m { @@ -130,12 +128,43 @@ func rebuildTexts(p CowyoData) { a = append(a, k) } sort.Sort(sort.Reverse(sort.IntSlice(a))) + + // Get the top 4 biggest diff times + var importantVersions []int + var r []versionsInfo for _, k := range a { for _, s := range n[k] { if s != 0 && s != len(n) { fmt.Printf("%d, %d\n", s, k) + importantVersions = append(importantVersions, s) + if len(importantVersions) > 3 { + sort.Ints(importantVersions) + for _, nn := range importantVersions { + r = append(r, versionsInfo{p.Timestamps[nn], nn}) + } + return r + } } } } - + sort.Ints(importantVersions) + for _, nn := range importantVersions { + r = append(r, versionsInfo{p.Timestamps[nn], nn}) + } + return r +} + +func rebuildTextsToDiffN(p CowyoData, n int) string { + dmp := diffmatchpatch.New() + lastText := "" + for i, diff := range p.Diffs { + seq1, _ := dmp.DiffFromDelta(lastText, diff) + texts_linemode := diffRebuildtexts(seq1) + rebuilt := texts_linemode[len(texts_linemode)-1] + if i == n { + return rebuilt + } + lastText = rebuilt + } + return "ERROR" }