github.com/decred/politeia@v1.4.0/politeiawww/cmd/pictl/pictl.go (about)

     1  // Copyright (c) 2017-2021 The Decred developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  	"os"
    11  	"time"
    12  
    13  	flags "github.com/jessevdk/go-flags"
    14  
    15  	"github.com/decred/dcrd/dcrutil/v3"
    16  	"github.com/decred/politeia/politeiawww/cmd/shared"
    17  )
    18  
    19  const (
    20  	// Config settings
    21  	defaultHomeDirname    = "pictl"
    22  	defaultDataDirname    = "data"
    23  	defaultConfigFilename = "pictl.conf"
    24  )
    25  
    26  var (
    27  	// Global variables for pictl commands
    28  	cfg    *shared.Config
    29  	client *shared.Client
    30  
    31  	// Config settings
    32  	defaultHomeDir = dcrutil.AppDataDir(defaultHomeDirname, false)
    33  )
    34  
    35  type pictl struct {
    36  	// This is here to prevent parsing errors caused by config flags.
    37  	Config shared.Config
    38  
    39  	// Basic commands
    40  	Help cmdHelp `command:"help"`
    41  
    42  	// Server commands
    43  	Version shared.VersionCmd `command:"version"`
    44  	Policy  policyCmd         `command:"policy"`
    45  	Login   shared.LoginCmd   `command:"login"`
    46  	Logout  shared.LogoutCmd  `command:"logout"`
    47  	Me      shared.MeCmd      `command:"me"`
    48  
    49  	// User commands
    50  	UserNew                 userNewCmd                   `command:"usernew"`
    51  	UserEdit                userEditCmd                  `command:"useredit"`
    52  	UserManage              shared.UserManageCmd         `command:"usermanage"`
    53  	UserEmailVerify         userEmailVerifyCmd           `command:"useremailverify"`
    54  	UserVerificationResend  userVerificationResendCmd    `command:"userverificationresend"`
    55  	UserPasswordReset       shared.UserPasswordResetCmd  `command:"userpasswordreset"`
    56  	UserPasswordChange      shared.UserPasswordChangeCmd `command:"userpasswordchange"`
    57  	UserUsernameChange      shared.UserUsernameChangeCmd `command:"userusernamechange"`
    58  	UserKeyUpdate           shared.UserKeyUpdateCmd      `command:"userkeyupdate"`
    59  	UserRegistrationPayment userRegistrationPaymentCmd   `command:"userregistrationpayment"`
    60  	UserPaymentsRescan      userPaymentsRescanCmd        `command:"userpaymentsrescan"`
    61  	UserProposalPaywall     userProposalPaywallCmd       `command:"userproposalpaywall"`
    62  	UserProposalPaywallTx   userProposalPaywallTxCmd     `command:"userproposalpaywalltx"`
    63  	UserProposalCredits     userProposalCreditsCmd       `command:"userproposalcredits"`
    64  	UserDetails             userDetailsCmd               `command:"userdetails"`
    65  	Users                   shared.UsersCmd              `command:"users"`
    66  
    67  	// Proposal commands
    68  	ProposalPolicy               cmdProposalPolicy               `command:"proposalpolicy"`
    69  	ProposalNew                  cmdProposalNew                  `command:"proposalnew"`
    70  	ProposalEdit                 cmdProposalEdit                 `command:"proposaledit"`
    71  	ProposalSetStatus            cmdProposalSetStatus            `command:"proposalsetstatus"`
    72  	ProposalSetBillingStatus     cmdProposalSetBillingStatus     `command:"proposalsetbillingstatus"`
    73  	ProposalBillingStatusChanges cmdProposalBillingStatusChanges `command:"proposalbillingstatuschanges"`
    74  	ProposalDetails              cmdProposalDetails              `command:"proposaldetails"`
    75  	ProposalTimestamps           cmdProposalTimestamps           `command:"proposaltimestamps"`
    76  	Proposals                    cmdProposals                    `command:"proposals"`
    77  	ProposalSummaries            cmdProposalSummaries            `command:"proposalsummaries"`
    78  	ProposalInv                  cmdProposalInv                  `command:"proposalinv"`
    79  	ProposalInvOrdered           cmdProposalInvOrdered           `command:"proposalinvordered"`
    80  	UserProposals                cmdUserProposals                `command:"userproposals"`
    81  
    82  	// Records commands
    83  	RecordPolicy cmdRecordPolicy `command:"recordpolicy"`
    84  
    85  	// Comments commands
    86  	CommentsPolicy    cmdCommentPolicy     `command:"commentpolicy"`
    87  	CommentNew        cmdCommentNew        `command:"commentnew"`
    88  	CommentEdit       cmdCommentEdit       `command:"commentedit"`
    89  	CommentVote       cmdCommentVote       `command:"commentvote"`
    90  	CommentCensor     cmdCommentCensor     `command:"commentcensor"`
    91  	CommentCount      cmdCommentCount      `command:"commentcount"`
    92  	Comments          cmdComments          `command:"comments"`
    93  	CommentVotes      cmdCommentVotes      `command:"commentvotes"`
    94  	CommentTimestamps cmdCommentTimestamps `command:"commenttimestamps"`
    95  
    96  	// Vote commands
    97  	VotePolicy      cmdVotePolicy      `command:"votepolicy"`
    98  	VoteAuthorize   cmdVoteAuthorize   `command:"voteauthorize"`
    99  	VoteStart       cmdVoteStart       `command:"votestart"`
   100  	CastBallot      cmdCastBallot      `command:"castballot"`
   101  	VoteDetails     cmdVoteDetails     `command:"votedetails"`
   102  	VoteResults     cmdVoteResults     `command:"voteresults"`
   103  	VoteSummaries   cmdVoteSummaries   `command:"votesummaries"`
   104  	VoteSubmissions cmdVoteSubmissions `command:"votesubmissions"`
   105  	VoteInv         cmdVoteInv         `command:"voteinv"`
   106  	VoteTimestamps  cmdVoteTimestamps  `command:"votetimestamps"`
   107  
   108  	// Dev commands
   109  	SendFaucetTx  cmdSendFaucetTx  `command:"sendfaucettx"`
   110  	TestRun       cmdTestRun       `command:"testrun"`
   111  	SeedProposals cmdSeedProposals `command:"seedproposals"`
   112  	VoteTestSetup cmdVoteTestSetup `command:"votetestsetup"`
   113  	VoteTest      cmdVoteTest      `command:"votetest"`
   114  	RFPTest       cmdRFPTest       `command:"rfptest"`
   115  	LegacyTest    cmdLegacyTest    `command:"legacytest"`
   116  
   117  	// Legacy www routes (deprecated)
   118  	TokenInventory shared.TokenInventoryCmd `command:"tokeninventory"`
   119  	ActiveVotes    cmdActiveVotes           `command:"activevotes"`
   120  }
   121  
   122  const helpMsg = `Application Options:
   123    -V, --version     Display version information and exit
   124        --appdata=    Path to application home directory
   125        --host=       politeiawww host
   126        --httscert    politeiawww https cert file path
   127        --skipverify  Skip verifying the server's certificate chain and host name
   128    -j, --json        Print raw JSON output
   129    -v, --verbose     Print verbose output
   130        --silent      Suppress all output
   131        --timer       Print command execution time stats
   132  
   133  Help commands
   134    help                         Print detailed help message for a command
   135  
   136  Basic commands
   137    version                      (public) Get politeiawww server version and CSRF
   138    policy                       (public) Get politeiawww server policy
   139    secret                       (public) Ping the server
   140    login                        (public) Login to politeiawww
   141    logout                       (user)   Logout from politeiawww
   142    me                           (user)   Get details of the logged in user
   143  
   144  User commands
   145    usernew                      (public) Create a new user
   146    useredit                     (user)   Edit the logged in user
   147    usermanage                   (admin)  Edit a user as an admin
   148    useremailverify              (public) Verify email address
   149    userverificationresend       (public) Resend verification email
   150    userpasswordreset            (public) Reset password 
   151    userpasswordchange           (user)   Change password
   152    userusernamechange           (user)   Change username
   153    userkeyupdate                (user)   Update user key (i.e. identity)
   154    userregistrationpayment      (user)   Verify registration payment
   155    userpaymentsrescan           (user)   Rescan all user payments
   156    userproposalpaywall          (user)   Get user paywall details
   157    userproposalpaywalltx        (user)   Get pending user payments
   158    userproposalcredits          (user)   Get user proposal credits
   159    userdetails                  (public) Get user details
   160    users                        (public) Get users
   161  
   162  Proposal commands
   163    proposalpolicy               (public) Get the pi api policy
   164    proposalnew                  (user)   Submit a new proposal
   165    proposaledit                 (user)   Edit an existing proposal
   166    proposalsetstatus            (admin)  Set the status of a proposal
   167    proposalsetbillingstatus     (admin)  Set the billing status of a proposal
   168    proposalbillingstatuschanges (public) Get billing status changes
   169    proposaldetails              (public) Get a full proposal record
   170    proposaltimestamps           (public) Get timestamps for a proposal
   171    proposals                    (public) Get proposals without their files
   172    proposalsummaries            (public) Get proposal summaries
   173    proposalinv                  (public) Get inventory by proposal status
   174    proposalinvordered           (public) Get inventory ordered chronologically
   175    userproposals                (public) Get proposals submitted by a user
   176  
   177  Record commands
   178    recordpolicy                 (public) Get the records api policy
   179  
   180  Comment commands
   181    commentpolicy                (public) Get the comments api policy
   182    commentnew                   (user)   Submit a new comment
   183    commentedit                  (user)   Edit a comment
   184    commentvote                  (user)   Upvote/downvote a comment
   185    commentcensor                (admin)  Censor a comment
   186    commentcount                 (public) Get the number of comments
   187    comments                     (public) Get comments
   188    commentvotes                 (public) Get comment votes
   189    commenttimestamps            (public) Get comment timestamps
   190  
   191  Vote commands
   192    votepolicy                   (public) Get the ticketvote api policy
   193    voteauthorize                (user)   Authorize a proposal vote
   194    votestart                    (admin)  Start a proposal vote
   195    castballot                   (public) Cast a ballot of votes
   196    votedetails                  (public) Get details for a vote
   197    voteresults                  (public) Get full vote results
   198    votesummaries                (public) Get vote summaries
   199    votesubmissions              (public) Get runoff vote submissions
   200    voteinv                      (public) Get proposal inventory by vote status
   201    votetimestamps               (public) Get vote timestamps
   202  
   203  Websocket commands
   204    subscribe                    (public) Subscribe/unsubscribe to websocket event
   205  
   206  Dev commands
   207    sendfaucettx                 Send a dcr faucet tx
   208    testrun                      Execute a test run of the pi routes
   209    seedproposals                Seed the backend with proposals
   210    votetestsetup                Setup a vote test
   211    votetest                     Execute a vote test
   212    rfptest                      Test RFP workflow
   213    legacytest                   Test legacy routes that do not have a command
   214  `
   215  
   216  func _main() error {
   217  	// Load config. The config variable is aglobal variable.
   218  	var err error
   219  	cfg, err = shared.LoadConfig(defaultHomeDir,
   220  		defaultDataDirname, defaultConfigFilename)
   221  	if err != nil {
   222  		return fmt.Errorf("load config: %v", err)
   223  	}
   224  
   225  	// Load client. The client variable is a global variable.
   226  	client, err = shared.NewClient(cfg)
   227  	if err != nil {
   228  		return fmt.Errorf("load client: %v", err)
   229  	}
   230  
   231  	// Setup global variables for shared commands
   232  	shared.SetConfig(cfg)
   233  	shared.SetClient(client)
   234  
   235  	// Check for a help flag. This is done separately so that we can
   236  	// print our own custom help message.
   237  	var opts flags.Options = flags.HelpFlag | flags.IgnoreUnknown |
   238  		flags.PassDoubleDash
   239  	parser := flags.NewParser(&struct{}{}, opts)
   240  	_, err = parser.Parse()
   241  	if err != nil {
   242  		var flagsErr *flags.Error
   243  		if errors.As(err, &flagsErr) && flagsErr.Type == flags.ErrHelp {
   244  			// The -h, --help flag was used. Print the custom help message
   245  			// and exit gracefully.
   246  			fmt.Printf("%v\n", helpMsg)
   247  			os.Exit(0)
   248  		}
   249  		return fmt.Errorf("parse help flag: %v", err)
   250  	}
   251  
   252  	// Setup timer stats
   253  	startTime := time.Now()
   254  
   255  	// Parse CLI args and execute command
   256  	parser = flags.NewParser(&pictl{Config: *cfg}, flags.Default)
   257  	_, err = parser.Parse()
   258  	if err != nil {
   259  		// An error has occurred during command execution. go-flags will
   260  		// have already printed the error to os.Stdout. Exit with an
   261  		// error code.
   262  		os.Exit(1)
   263  	}
   264  
   265  	// Print timer stats
   266  	if cfg.Timer {
   267  		stopTime := time.Now()
   268  		printf("---Timer Stats---\n")
   269  		printf("  Start  : %v\n", dateAndTimeFromUnix(startTime.Unix()))
   270  		printf("  Stop   : %v\n", dateAndTimeFromUnix(stopTime.Unix()))
   271  		printf("  Elapsed: %v\n", stopTime.Sub(startTime))
   272  	}
   273  
   274  	return nil
   275  }
   276  
   277  func main() {
   278  	err := _main()
   279  	if err != nil {
   280  		fmt.Fprintf(os.Stderr, "%v\n", err)
   281  		os.Exit(1)
   282  	}
   283  }