Compare commits

...
Sign in to create a new pull request.

57 commits

Author SHA1 Message Date
RustamOper05
51a2940e53 Merge pull request 'fix_back' (#20) from fix_back into master
Reviewed-on: https://codeberg.org/NaMe2te/Blog/pulls/20
2024-01-18 22:07:25 +00:00
06e281c1a8 delete front 2024-01-19 01:05:35 +03:00
90aa236efb merge branches and delete front 2024-01-19 01:03:49 +03:00
867e7fdc9e Merge branch 'new_back_new' 2024-01-19 01:01:19 +03:00
78d398b0be fix confl 2024-01-19 00:58:18 +03:00
ecc94cace6 fix spaces 2024-01-19 00:53:02 +03:00
d5126a94e4 fix spaces 2024-01-19 00:52:15 +03:00
956395df8a delete compiled files 2024-01-19 00:46:31 +03:00
d09455e06f delete compiled files 2024-01-19 00:42:25 +03:00
d89fc3b31f fix backend 2024-01-19 00:37:48 +03:00
720eb16d72 fix: backend 2024-01-18 18:17:43 +03:00
ef2b1ec82c feat: front 2024-01-18 15:07:30 +03:00
9968be4cd9 delete: _deploy 2024-01-17 22:14:02 +03:00
674c1bf358 delete: dislikes 2024-01-17 21:55:34 +03:00
efc1d5eafe fix: post hash 2024-01-17 21:52:35 +03:00
RustamOper05
11cfa20533 Merge pull request 'add get req' (#16) from new_back_new into master
Reviewed-on: https://codeberg.org/NaMe2te/Blog/pulls/16
2024-01-17 18:42:24 +00:00
maksaid
5abd38c4e6 Merge pull request 'add: gas transfer' (#15) from gas_transfer into master
Reviewed-on: https://codeberg.org/NaMe2te/Blog/pulls/15
2024-01-17 18:42:10 +00:00
46c6e5c2ae add get req 2024-01-17 21:20:18 +03:00
9aa04d2d19 add: gas transfer 2024-01-17 18:54:48 +03:00
RustamOper05
5a6cd4bbb8 Merge pull request 'fix backend' (#14) from add_ШУШ into master
Reviewed-on: https://codeberg.org/NaMe2te/Blog/pulls/14
2024-01-17 14:10:57 +00:00
RustamOper05
0b7874e00e Merge pull request 'test_comments' (#13) from test_comments into master
Reviewed-on: https://codeberg.org/NaMe2te/Blog/pulls/13
2024-01-17 14:10:24 +00:00
9f016ed9ab nu normalno pofixil da 2024-01-17 17:08:52 +03:00
3b3191bfb9 fix backend 2024-01-17 17:06:03 +03:00
259f1aa1e5 fix comments 2024-01-17 16:17:22 +03:00
RustamOper05
accc23b6b3 Merge pull request 'halich' (#12) from underground into master
Reviewed-on: https://codeberg.org/NaMe2te/Blog/pulls/12
2024-01-17 11:25:52 +00:00
6f0d12dec1 halich 2024-01-17 14:24:23 +03:00
RustamOper05
4858338a04 Merge pull request 'cringe_backend' (#10) from cringe_backend into master
Reviewed-on: https://codeberg.org/NaMe2te/Blog/pulls/10
2024-01-17 10:36:16 +00:00
a08d9ebc61 add backend poteryal misl 2024-01-17 13:34:50 +03:00
0e16887aab add backend 2024-01-17 13:30:37 +03:00
RustamOper05
792708dd07 Merge pull request 'cringe_branch' (#9) from cringe_branch into master
Reviewed-on: https://codeberg.org/NaMe2te/Blog/pulls/9
2024-01-17 09:39:12 +00:00
e97733fa6f delete compil files 2024-01-17 12:34:02 +03:00
8d90e22772 add post validation 2024-01-17 12:31:41 +03:00
892f607cd0 delete usls logs from post 2024-01-17 12:26:20 +03:00
125cb1ad63 delete compil files 2024-01-17 12:24:08 +03:00
547efeb914 update gitignore 2024-01-17 04:57:49 +03:00
80f57e3327 feat: add back asp net 2024-01-17 01:08:20 +03:00
cb81ed0aea этот коммит никогда не будет запушен 2024-01-16 22:19:30 +03:00
d62a6daa4f remove: forum 2024-01-16 18:38:25 +03:00
RustamOper05
1b152f2b77 Merge pull request 'new_backend' (#8) from new_backend into master
Reviewed-on: https://codeberg.org/NaMe2te/Blog/pulls/8
2024-01-16 14:32:19 +00:00
e334c3fb9d fix comment 2024-01-16 17:30:21 +03:00
d1d6b51c80 fix: merge 2024-01-16 16:29:47 +03:00
974a9c9be6 Merge branch 'post-brench' 2024-01-16 16:29:00 +03:00
1c7d169c21 feat: get by login, get comment in post, add saving comment by comment id 2024-01-16 16:00:16 +03:00
8224f25c18 fix: initial index 2024-01-16 15:11:13 +03:00
d33e0d9058 taking h 2024-01-16 14:54:54 +03:00
22b871e07e fix: post id's 2024-01-16 14:53:55 +03:00
0358a1f918 loading initial state on start 2024-01-16 14:42:01 +03:00
RustamOper05
2a22f14509 Merge pull request 'fix types convert' (#6) from day_x_fix_all into master
Reviewed-on: https://codeberg.org/NaMe2te/Blog/pulls/6
2024-01-16 09:00:33 +00:00
dc9f6a73aa fix types convert 2024-01-15 23:09:10 +03:00
RustamOper05
e819d8ce2c Merge pull request 'add: post methods, posts storage' (#5) from post-branch into master
Reviewed-on: https://codeberg.org/NaMe2te/Blog/pulls/5
2024-01-15 17:00:18 +00:00
cee71a5c35 add: post methods, posts storage 2024-01-15 15:26:08 +03:00
RustamOper05
7346f728e9 ( ^ ʖ ^) 2024-01-14 21:51:55 +03:00
RustamOper05
909cdc50b5 fix conflicts 2024-01-14 21:48:44 +03:00
RustamOper05
6bf5e6095c Merge branch 'oracle_uuid' 2024-01-14 21:47:16 +03:00
7326d7046e Merge branch 'comments' with new imports 2024-01-13 16:48:31 +03:00
c00519038a Merge branch 'comments' 2024-01-08 16:23:24 +03:00
5580931d5f fix: imports 2024-01-08 16:20:33 +03:00
19 changed files with 977 additions and 108 deletions

489
.gitignore vendored Normal file → Executable file
View file

@ -21,3 +21,492 @@
# Go workspace file # Go workspace file
go.work go.work
# Created by https://www.toptal.com/developers/gitignore/api/rider
# Edit at https://www.toptal.com/developers/gitignore?templates=rider
### Rider ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
# End of https://www.toptal.com/developers/gitignore/api/rider
# Created by https://www.toptal.com/developers/gitignore/api/visualstudio
# Edit at https://www.toptal.com/developers/gitignore?templates=visualstudio
### VisualStudio ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
### VisualStudio Patch ###
# Additional files built by Visual Studio
# End of https://www.toptal.com/developers/gitignore/api/visualstudio

0
.idea/.gitignore generated vendored Normal file → Executable file
View file

0
.idea/Blog.iml generated Normal file → Executable file
View file

0
.idea/modules.xml generated Normal file → Executable file
View file

0
.idea/vcs.xml generated Normal file → Executable file
View file

161
Comment/comment.go Normal file → Executable file
View file

@ -1,69 +1,85 @@
package Comment package Comment
import ( import (
"github.com/nspcc-dev/neo-go/pkg/interop/native/oracle" "github.com/nspcc-dev/neo-go/pkg/interop"
"github.com/nspcc-dev/neo-go/pkg/interop/iterator"
"github.com/nspcc-dev/neo-go/pkg/interop/native/gas"
"github.com/nspcc-dev/neo-go/pkg/interop/native/std" "github.com/nspcc-dev/neo-go/pkg/interop/native/std"
"github.com/nspcc-dev/neo-go/pkg/interop/runtime" "github.com/nspcc-dev/neo-go/pkg/interop/runtime"
"github.com/nspcc-dev/neo-go/pkg/interop/storage" "github.com/nspcc-dev/neo-go/pkg/interop/storage"
) )
type Comment struct { type Comment struct {
id string id string
authorId string userLogin string
postId string postId string
text string text string
likes int likes int
dislikes int
} }
func CreateNewComment(authorId string, postId string, text string) { const (
comment_prefix = "comment_"
user_comment_count_prefix = "comment_count_"
gas_decimals = 1_0000_0000
comment_hash = "comment_hash"
)
func _deploy(data interface{}, isUpdate bool) {
if isUpdate {
return
}
ctx := storage.GetContext()
storage.Put(ctx, "index_comment", "0")
}
func CreateNewComment(userLogin string, postId string, text string) {
ctx := storage.GetContext() ctx := storage.GetContext()
id := std.Atoi10(storage.Get(ctx, "index_comment").(string))
id++
storage.Put(ctx, "index_comment", std.Itoa10(id))
if storage.Get(ctx, user_comment_count_prefix+userLogin) == nil {
storage.Put(ctx, user_comment_count_prefix+userLogin, 0)
}
commentId := comment_prefix + std.Itoa10(id)
newComment := Comment{ newComment := Comment{
id: "none", id: commentId,
authorId: authorId, userLogin: userLogin,
postId: postId, postId: postId,
text: text, text: text,
likes: 0, likes: 0,
dislikes: 0,
} }
var comments = make([]Comment, 0)
storeURL := "https://www.uuidgenerator.net/api/version7" comments = GetByPostId(postId)
oracle.Request(storeURL, nil, "cbGetUUID", nil, oracle.MinimumResponseGas)
newComment.id = storage.Get(ctx, "lastCommentId").(string)
comments := GetByPostId(postId)
comments = append(comments, newComment) comments = append(comments, newComment)
storage.Put(ctx, postId+"_comment", std.Serialize(comments)) storage.Put(ctx, comment_prefix+postId, std.Serialize(comments)) // { "comment_post_{i} : comments.json"}
} storage.Put(ctx, commentId, std.Serialize(newComment)) // { "comment_{i}" : comment.json}
func cbGetUUID(url string, commentData any, code int, result []byte) { commentCount := storage.Get(ctx, user_comment_count_prefix+userLogin).(int)
callingHash := runtime.GetCallingScriptHash() commentCount++
if !callingHash.Equals(oracle.Hash) { storage.Put(ctx, user_comment_count_prefix+userLogin, commentCount) // { "comment_count_{login}" : {i} }
panic("not called from the oracle contract") storage.Put(ctx, userLogin+"_c_"+std.Itoa10(commentCount), commentId) // { "{login}_c_{i} : comment_{i} }
}
if code != oracle.Success {
panic("request failed for " + url + " with code " + std.Itoa(code, 10))
}
runtime.Log("result for " + url + " is: " + string(result))
runtime.Log("Last Comment id is: " + string(result)) runtime.Log("Comment created: " + commentId + " ----- " + user_comment_count_prefix + userLogin + " ------ " + userLogin + "_c_" + std.Itoa10(commentCount))
ctx := storage.GetContext()
storage.Put(ctx, "lastCommentId", string(result))
} }
func GetByPostId(postId string) []Comment { func GetByPostId(postId string) []Comment {
ctx := storage.GetContext() ctx := storage.GetContext()
return std.Deserialize(storage.Get(ctx, postId+"_comment").([]byte)).([]Comment) comments := storage.Get(ctx, comment_prefix+postId)
if comments == nil {
storage.Put(ctx, comment_prefix+postId, std.Serialize(make([]Comment, 0)))
}
return std.Deserialize(storage.Get(ctx, comment_prefix+postId).([]byte)).([]Comment)
} }
func GetByAuthorId(postId string, authorId string) []Comment { func GetByLoginInPost(postId string, login string) []Comment {
comments := GetByPostId(postId) comments := GetByPostId(postId)
var commentsByAuthor []Comment var commentsByAuthor []Comment
for _, comment := range comments { for _, comment := range comments {
if comment.authorId == authorId { if comment.userLogin == login {
commentsByAuthor = append(commentsByAuthor, comment) commentsByAuthor = append(commentsByAuthor, comment)
} }
} }
@ -71,36 +87,53 @@ func GetByAuthorId(postId string, authorId string) []Comment {
return commentsByAuthor return commentsByAuthor
} }
func GetComment(commentId string, postId string) Comment { func GetByLogin(login string) []Comment {
comments := GetByPostId(postId) var comments []Comment = make([]Comment, 0)
for _, comment := range comments {
if comment.id == commentId {
return comment
}
}
panic("Коммента с таким айдишником нету")
}
func RateComment(isLike bool, postId string, commentId string) {
comment := GetComment(commentId, postId)
if isLike {
comment.likes++
} else {
comment.dislikes++
}
UpdateComment(comment, postId)
}
func UpdateComment(comment Comment, postId string) {
ctx := storage.GetContext() ctx := storage.GetContext()
comments := GetByPostId(postId) it := storage.Find(ctx, login+"_c_", storage.ValuesOnly|storage.DeserializeValues)
for iterator.Next(it) {
commentId := iterator.Value(it).(string)
comments = append(comments, GetComment(commentId))
}
return comments
}
func GetComment(commentId string) Comment {
ctx := storage.GetContext()
comment := storage.Get(ctx, commentId)
if comment == nil {
panic("comment not found")
}
return std.Deserialize(comment.([]byte)).(Comment)
}
func Rate(commentId string, walletHashFrom interop.Hash160) {
ctx := storage.GetContext()
comment := GetComment(commentId)
success := gas.Transfer(walletHashFrom, storage.Get(ctx, comment.userLogin+"_hash").(interop.Hash160), gas_decimals, nil)
if !success {
panic("gas transfer failed")
} else {
comment.likes += 1
updateComment(comment)
}
}
func updateComment(comment Comment) {
ctx := storage.GetContext()
comments := GetByPostId(comment.postId)
for i := 0; i < len(comments); i++ { for i := 0; i < len(comments); i++ {
if comments[i].id == comment.id { if comments[i].id == comment.id {
comments[i] = comment comments[i] = comment
} }
} }
storage.Put(ctx, postId+"_comment", std.Serialize(comments)) storage.Put(ctx, comment_prefix+comment.postId, std.Serialize(comments))
storage.Put(ctx, comment.id, std.Serialize(comment))
}
func GetContractHash() interop.Hash160 {
ctx := storage.GetContext()
return storage.Get(ctx, comment_hash).(interop.Hash160)
} }

0
Comment/comment.yml Normal file → Executable file
View file

View file

@ -1,5 +0,0 @@
package Forums
type Forum struct {
threads []string
}

0
Models/categories.json Normal file → Executable file
View file

109
Post/post_contract.go Normal file → Executable file
View file

@ -1,7 +1,9 @@
package Post package Post
import ( import (
"github.com/nspcc-dev/neo-go/pkg/interop/native/oracle" "github.com/nspcc-dev/neo-go/pkg/interop"
"github.com/nspcc-dev/neo-go/pkg/interop/iterator"
"github.com/nspcc-dev/neo-go/pkg/interop/native/gas"
"github.com/nspcc-dev/neo-go/pkg/interop/native/std" "github.com/nspcc-dev/neo-go/pkg/interop/native/std"
"github.com/nspcc-dev/neo-go/pkg/interop/runtime" "github.com/nspcc-dev/neo-go/pkg/interop/runtime"
"github.com/nspcc-dev/neo-go/pkg/interop/storage" "github.com/nspcc-dev/neo-go/pkg/interop/storage"
@ -9,56 +11,52 @@ import (
type Post struct { type Post struct {
postName string postName string
header string
text string text string
authorId string login string
category string
likes int likes int
dislikes int
id string id string
} }
const ( const (
lastIndex = "_lastIndex" lastIndex = "user_post_index"
id = "current_post_id"
comment_prefix = "comment_"
gas_decimals = 1_0000_0000
) )
func NewPost(authorId string, text string, postName string) { func NewPost(login string, text string, postName string) {
ctx := storage.GetContext() ctx := storage.GetContext()
updatePostId()
id := storage.Get(ctx, id).(int)
post_id := "post_" + std.Itoa10(id)
post := Post{ post := Post{
text: text, text: text,
authorId: authorId, login: login,
dislikes: 0,
likes: 0, likes: 0,
category: "none",
postName: postName, postName: postName,
id: "none", id: post_id,
} }
storeURL := "https://www.uuidgenerator.net/api/version7"
oracle.Request(storeURL, nil, "cbGetUUID", nil, oracle.MinimumResponseGas)
post.id = storage.Get(ctx, "lastPostId").(string)
storage.Put(ctx, post.id, std.Serialize(post)) storage.Put(ctx, post.id, std.Serialize(post))
updatePostIndex(authorId) updatePostIndex(login)
lastPostIndex := storage.Get(ctx, authorId+lastIndex) lastPostIndex := storage.Get(ctx, login+lastIndex).(int)
storage.Put(ctx, login+"_p_"+std.Itoa10(lastPostIndex), post.id)
storage.Put(ctx, authorId+lastPostIndex.(string), post.id) runtime.Log("Post created. Post id: " + post.id + "; User post id" + login + "_p_" + std.Itoa10(lastPostIndex))
} }
func CbGetUUID(url string, postData any, code int, result []byte) { func GetAllPosts() []Post {
callingHash := runtime.GetCallingScriptHash() posts := make([]Post, 0)
if !callingHash.Equals(oracle.Hash) { ctx := storage.GetReadOnlyContext()
panic("not called from the oracle contract") it := storage.Find(ctx, "post", storage.ValuesOnly|storage.DeserializeValues)
for iterator.Next(it) {
post := iterator.Value(it).(Post)
runtime.Log(string(std.Serialize(post)))
posts = append(posts, post)
} }
if code != oracle.Success {
panic("request failed for " + url + " with code " + std.Itoa(code, 10))
}
runtime.Log("result for " + url + " is: " + string(result))
ctx := storage.GetContext() return posts
storage.Put(ctx, "lastPostId", string(result))
} }
func GetPost(postId string) Post { func GetPost(postId string) Post {
@ -72,20 +70,48 @@ func GetPost(postId string) Post {
return std.Deserialize(data.([]byte)).(Post) return std.Deserialize(data.([]byte)).(Post)
} }
func RatePost(isLike bool, postId string) { func GetAllPostsByUser(login string) []Post {
ctx := storage.GetReadOnlyContext()
var postsByUser []Post = make([]Post, 0)
i := 1
n := getPostIndex(login)
for i < n+1 {
post_key := storage.Get(ctx, login+"_p_"+std.Itoa10(i))
if post_key == nil {
panic("post key not found")
}
post_key = post_key.(string)
post := storage.Get(ctx, post_key)
if post == nil {
panic("post not found")
}
i++
postsByUser = append(postsByUser, std.Deserialize(post.([]byte)).(Post))
}
return postsByUser
}
func Rate(postId string, walletHashFrom interop.Hash160) {
ctx := storage.GetContext() ctx := storage.GetContext()
post := GetPost(postId) post := GetPost(postId)
if isLike { success := gas.Transfer(walletHashFrom, storage.Get(ctx, post.login+"_hash").(interop.Hash160), gas_decimals, nil)
post.likes++ if !success {
panic("gas transfer failed")
} else { } else {
post.dislikes++ post.likes += 1
storage.Put(ctx, post.id, std.Serialize(post))
} }
storage.Put(ctx, post.id, std.Serialize(post))
} }
func getPostIndex(userId string) int { func getPostIndex(userId string) int {
ctx := storage.GetContext() ctx := storage.GetContext()
index := storage.Get(ctx, userId+lastIndex) index := storage.Get(ctx, userId+lastIndex)
if index == nil {
index = 0
}
return index.(int) return index.(int)
} }
@ -94,3 +120,18 @@ func updatePostIndex(userId string) {
index := getPostIndex(userId) index := getPostIndex(userId)
storage.Put(ctx, userId+lastIndex, index+1) storage.Put(ctx, userId+lastIndex, index+1)
} }
func getPostId() int {
ctx := storage.GetContext()
current_id := storage.Get(ctx, id)
if current_id == nil {
current_id = 0
}
return current_id.(int)
}
func updatePostId() {
ctx := storage.GetContext()
cur_id := getPostId()
storage.Put(ctx, id, cur_id+1)
}

View file

@ -3,4 +3,4 @@ safemethods: []
supportedstandards: [] supportedstandards: []
events: events:
permissions: permissions:
- methods: ["request"] - methods: "*"

0
README.md Normal file → Executable file
View file

View file

@ -2,6 +2,7 @@ package Users
import ( import (
"github.com/nspcc-dev/neo-go/pkg/interop" "github.com/nspcc-dev/neo-go/pkg/interop"
"github.com/nspcc-dev/neo-go/pkg/interop/contract"
"github.com/nspcc-dev/neo-go/pkg/interop/native/std" "github.com/nspcc-dev/neo-go/pkg/interop/native/std"
"github.com/nspcc-dev/neo-go/pkg/interop/runtime" "github.com/nspcc-dev/neo-go/pkg/interop/runtime"
"github.com/nspcc-dev/neo-go/pkg/interop/storage" "github.com/nspcc-dev/neo-go/pkg/interop/storage"
@ -21,7 +22,6 @@ const (
func NewUser(name string, surname string, login string, password string, owner interop.Hash160) { func NewUser(name string, surname string, login string, password string, owner interop.Hash160) {
ctx := storage.GetContext() ctx := storage.GetContext()
existing_login := storage.Get(ctx, login) existing_login := storage.Get(ctx, login)
if existing_login != nil { if existing_login != nil {
panic("this login is taken by someone else") panic("this login is taken by someone else")
@ -36,9 +36,19 @@ func NewUser(name string, surname string, login string, password string, owner i
} }
saveUser(ctx, login, user) saveUser(ctx, login, user)
} }
func GetUser(ctx storage.Context, login string) User { func GetUser(login string) User {
return getUserTst(storage.GetReadOnlyContext(), login)
}
func RateForGas(commentId string, contractHash interop.Hash160, login string) {
ctx := storage.GetContext()
contract.Call(contractHash, "rate", contract.ReadOnly, commentId, storage.Get(ctx, login+"_hash"))
}
func getUserTst(ctx storage.Context, login string) User {
data := storage.Get(ctx, login) data := storage.Get(ctx, login)
if data == nil { if data == nil {
@ -51,6 +61,6 @@ func GetUser(ctx storage.Context, login string) User {
func saveUser(ctx storage.Context, userLogin string, user User) { func saveUser(ctx storage.Context, userLogin string, user User) {
runtime.Log("User " + userLogin + " was created") runtime.Log("User " + userLogin + " was created")
storage.Put(ctx, userLogin+lastIndex, -1) storage.Put(ctx, userLogin+"_hash", user.ownerHash)
storage.Put(ctx, userLogin, std.Serialize(user)) storage.Put(ctx, userLogin, std.Serialize(user))
} }

214
backend/backend.py Normal file
View file

@ -0,0 +1,214 @@
import http.server
import socketserver
import subprocess
from urllib.parse import urlparse, parse_qs
import base64
import json
import re
def compile_and_deploy_contract(
user_path: str,
post_path: str,
comment_path: str,
password: str,
node_wallet: str,
run_start_funcs: bool=False
) -> dict[str, str]:
user_compile_command = f"sshpass -p {password} neo-go contract compile -i {user_path}/user.go -c {user_path}/user.yml -m {user_path}/user.json"
subprocess.run(user_compile_command, shell=True, check=False)
user_deploy_command = f"sshpass -p {password} neo-go contract deploy -i {user_path}/user.nef -w {node_wallet} -r http://localhost:30333 -m {user_path}/user.json --force"
proc = subprocess.Popen(user_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
user_out_list = []
while True:
line = proc.stdout.readline()
if not line:
break
user_out_list.append(line.rstrip())
user_hash = str(user_out_list[-1], encoding='utf-8').replace("Contract: ", "")
post_compile_command = f"sshpass -p {password} neo-go contract compile -i {post_path}/post_contract.go -c {post_path}/post_contract.yml -m {post_path}/post_contract.json"
subprocess.run(post_compile_command, shell=True, check=False)
post_deploy_command = f"sshpass -p {password} neo-go contract deploy -i {post_path}/post_contract.nef -w {node_wallet} -r http://localhost:30333 -m {post_path}/post_contract.json --force"
proc = subprocess.Popen(post_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
post_out_list = []
while True:
line = proc.stdout.readline()
if not line:
break
post_out_list.append(line.rstrip())
post_hash = str(post_out_list[-1], encoding='utf-8').replace("Contract: ", "")
comment_compile_command = f"sshpass -p {password} neo-go contract compile -i {comment_path}/comment.go -c {comment_path}/comment.yml -m {comment_path}/comment.json"
subprocess.run(comment_compile_command, shell=True, check=False)
comment_deploy_command = f"sshpass -p {password} neo-go contract deploy -i {comment_path}/comment.nef -w {node_wallet} -r http://localhost:30333 -m {comment_path}/comment.json --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_out_list = []
while True:
line = proc.stdout.readline()
if not line:
break
comment_out_list.append(line.rstrip())
comment_hash = str(comment_out_list[-1], encoding='utf-8').replace("Contract: ", "")
print(user_hash, post_hash, comment_hash)
if run_start_funcs:
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {user_hash} newUser user_test1 user_test1 user_test1 1 Nhfg3TbpwogLvDGVvAvqyThbsHgoSUKwtn --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {user_hash} newUser user_test2 user_test2 user_test2 1 Nhfg3TbpwogLvDGVvAvqyThbsHgoSUKwtn --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {post_hash} newPost user_test1 test test --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {post_hash} newPost user_test2 test test --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {comment_hash} createNewComment user_test1 post_1 some_text --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {comment_hash} createNewComment user_test1 post_1 some_text --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {comment_hash} createNewComment user_test2 post_1 some_text --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
return user_hash, post_hash, comment_hash
user_hash, post_hash, comment_hash = compile_and_deploy_contract(
"../User",
"../Post",
"../Comment",
"one",
"/home/ftmi-krasotka/Desktop/frostfs_test/frostfs-aio/morph/node-wallet.json",
True
)
class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
with open("./route.json", "r") as f:
route_dict = json.load(f)
with open("logs.log", "w") as f:
f.write("starting...")
with open("logs.log", "a") as f:
f.write(f"user_hash: {user_hash}\npost_hash: {post_hash}\ncomment_hash: {comment_hash}")
parsed_path = urlparse(self.path)
query = parse_qs(parsed_path.query)
if "command_type" in query and "command_id" in query:
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
params = query.get("args", None)
parsed_params = " " + ' '.join(params) if params else ""
command_type = query["command_type"][0]
contract_name = query["contract"][0]
method = query["method"][0]
with open("logs.log", "a") as f:
f.write("reading params...\n")
if command_type == "get":
hash_for_req = None
if contract_name == "post":
hash_for_req = post_hash
elif contract_name == "user":
hash_for_req = user_hash
elif contract_name == "comment":
hash_for_req = comment_hash
with open("logs.log", "a") as f:
f.write(f"params: {[command_type, contract_name, method, parsed_params]}\n")
command = f"neo-go contract testinvokefunction -r http://localhost:30333 {hash_for_req} {method}{parsed_params}"
print(command)
proc = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out_list = []
while True:
if proc.stdout is None:
break
line = proc.stdout.readline()
if not line:
break
out_list.append(line.rstrip())
answer = " ".join(map(lambda x: x.decode("utf-8"), out_list))
answer = re.sub(r"[\n\t\s]*", "", answer)
print(json.loads(answer)["stack"][0])
if json.loads(answer)["stack"][0]["type"] == "Struct":
answer_dict = json.loads(answer)["stack"][0]["value"]
obj_fiedls = []
for field in answer_dict:
if field["type"] in ["ByteString", "Buffer"]:
encoded_string = field["value"]
result_string = base64.b64decode(encoded_string)
try:
result_string = result_string.decode('utf-8')
except:
pass
obj_fiedls.append(result_string)
elif field["type"] == "Integer":
encoded_string = field["value"]
obj_fiedls.append(encoded_string)
self.wfile.write(bytes(f"{obj_fiedls}", "utf-8"))
else:
answer_dict = json.loads(answer)["stack"][0]["value"]
answer_list = []
for obj_i in answer_dict:
obj = obj_i["value"]
obj_fiedls = []
for field in obj:
if field["type"] in ["ByteString", "Buffer"]:
encoded_string = field["value"]
result_string = base64.b64decode(encoded_string)
result_string = result_string.decode('utf-8')
obj_fiedls.append(result_string)
elif field["type"] == "Integer":
encoded_string = field["value"]
obj_fiedls.append(encoded_string)
answer_list.append(obj_fiedls)
self.wfile.write(bytes(f"{answer_list}", "utf-8"))
else:
self.send_response(400)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("Bad request", "utf-8"))
if __name__ == "__main__":
PORT = 2281
Handler = MyHttpRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("Сервер запущен на порту", PORT)
httpd.serve_forever()
httpd.server_close()

70
backend/edit_route.py Normal file
View file

@ -0,0 +1,70 @@
import json
route = {
"1": {
"command": "neo-go wallet init",
"flags": {
"wallet": "wallet file name",
"account": "create new account"
}
},
"2": {
"command": "neo-go wallet dump-keys",
"flags": {
"wallet": "wallet file name",
}
},
"3": {
"command": "neo-go wallet nep17 balance",
"flags": {
"wallet": "wallet file name",
}
},
"4": {
"command": "neo-go wallet nep17 transfer",
"flags": {
"wallet": "wallet file name(wallet from which transfer is made)",
"from": "hash of wallet from which transfer is made",
"to" : "hash of wallet to which transfer is made",
"amount": "gas transfer amount",
"token": "token for transfer NEO/GAS",
}
},
"5": {
"command": "neo-go contract compile",
"flags": {
"in": "smart contract file name(*.go)",
"manifest": "contract manifest file name(*.json)",
"contract_config" : "contract config file name(*.yml)",
}
},
"6": {
"command": "neo-go contract deploy",
"flags": {
"wallet": "wallet file name",
"in": "compiled smart contract file name(*.nef)",
"manifest" : "manifest file name(*.json)",
}
},
"7": {
"command": "neo-go contract invokefunction",
"flags": {
"wallet": "wallet file name",
"contract_hash": "hash of contract",
"func_name": "name of invoked func",
"parameters": "list([]) of func parameters"
}
},
"8": {
"command": "neo-go contract testinvokefunction",
"flags": {
"contract_hash": "hash of contract",
"func_name": "name of invoked func",
"parameters": "list([]) of func parameters"
}
}
}
with open("route.json", "w") as f:
f.write(json.dumps(route))

14
backend/req_test.py Normal file
View file

@ -0,0 +1,14 @@
import requests
# Отправляем GET запрос на сервер
response = requests.get(
'http://localhost:2281',
params={
"command_type": "get",
"method": "getPost",
"command_id": "8",
"contract": "post",
"args": ["post_1"]})
# Выводим ответ от сервера
print('Ответ от сервера:', response.text)

1
backend/route.json Normal file
View file

@ -0,0 +1 @@
{"1": {"command": "neo-go wallet init", "flags": {"wallet": "wallet file name", "account": "create new account"}}, "2": {"command": "neo-go wallet dump-keys", "flags": {"wallet": "wallet file name"}}, "3": {"command": "neo-go wallet nep17 balance", "flags": {"wallet": "wallet file name"}}, "4": {"command": "neo-go wallet nep17 transfer", "flags": {"wallet": "wallet file name(wallet from which transfer is made)", "from": "hash of wallet from which transfer is made", "to": "hash of wallet to which transfer is made", "amount": "gas transfer amount", "token": "token for transfer NEO/GAS"}}, "5": {"command": "neo-go contract compile", "flags": {"in": "smart contract file name(*.go)", "manifest": "contract manifest file name(*.json)", "contract_config": "contract config file name(*.yml)"}}, "6": {"command": "neo-go contract deploy", "flags": {"wallet": "wallet file name", "in": "compiled smart contract file name(*.nef)", "manifest": "manifest file name(*.json)"}}, "7": {"command": "neo-go contract invokefunction", "flags": {"wallet": "wallet file name", "contract_hash": "hash of contract", "func_name": "name of invoked func", "parameters": "list([]) of func parameters"}}, "8": {"command": "neo-go contract testinvokefunction", "flags": {"contract_hash": "hash of contract", "func_name": "name of invoked func", "parameters": "list([]) of func parameters"}}}

4
go.mod Normal file → Executable file
View file

@ -2,4 +2,6 @@ module blog
go 1.21.5 go 1.21.5
require github.com/nspcc-dev/neo-go/pkg/interop v0.0.0-20231219060339-de98b39a9502 require (
github.com/nspcc-dev/neo-go/pkg/interop v0.0.0-20231219060339-de98b39a9502
)

0
go.sum Normal file → Executable file
View file